entry and loop in python - python

I want to write a program that accept input from users multiple times. Calculate and print the average age as well as the number of males and females. Every time I run the script I get ZeroDivisionError: integer division or modulo by zero Also when I use the sum(ages) it returns 0. I need help please
print('Enter the required lines of text.')
print('Enter an empty line to quit.')
print('For sex enter M for male and F for female.')
print ('_____________________________________________________________')
# Start with a list containing several names.
names = list()
genders = list()
ages = list()
total = sum(ages)
average = total / len(ages)
# variables to append
new_name = raw_input('Enter Name: ')
new_sex = raw_input('Enter Sex: ')
new_age = raw_input('Enter Age: ')
# while NOT the termination condition
while new_name != '':
names.append(new_name)
genders.append(new_sex)
ages.append(new_age)
new_name = raw_input('Enter Name: ')
new_sex = raw_input('Enter Sex: ')
new_age = raw_input('Enter Age: ') # !! reset value at end of loop!
print('The sum of age is:', total)
for new_name in names:
for new_age in ages:
for new_sex in genders:
print(names)
print(genders)
print(ages)
print(average)

Here is the problem:
average = total / len(ages)
there is only one division in the code... so that is not big surprise, where division by zero happens.
If you have a list o users - keep it like that:
users = list()
name = raw_input('Enter Name: ')
sex = raw_input('Enter Sex: ')
age = raw_input('Enter Age: ')
user = {'name': name, 'age': age, 'sex': sex}
users.append(user)
You can do raw_input inside while loop, without that initial part. Just query, and append.
To avoid error - calculate information after input. Right now - average is calculated with zero input...
Final for loops - for every name you call another loop, where for every age, you call another loop where for every sex... I don't think it is what is needed. With your design - assume that all list has same length, create iterator, and get elements by index. Then be sure lists are with same length. Or... use users.

I was able to figure it out. Thanks to everyone for the help and support
genders = list()
ages = list()
# holds the gender ages
genderm = list()
genderf = list()
countm = list()
countf = list()
# while loop for termination condition
while True:
new_name = raw_input('Enter Name: ')
new_sex = raw_input('Enter Sex: ')
new_age = int(raw_input('Enter Age: '))
# Append the input to the list
names.append(new_name)
genders.append(new_sex)
ages.append(new_age)
# Male age count
if new_sex == 'M':
countm.append(new_age)
genderm.append(new_sex)
# Female age count
elif new_sex == 'F':
countf.append(new_age)
genderf.append(new_sex)
# !! reset value at end of loop!
testanswer = raw_input('Press y to make another entry')
if testanswer.upper() == 'Y':
continue
# result of the input
print('Number of Females (F): ', genders.count('F'))
print('Number of Males (M): ', genders.count('M'))
print('Average Male Age: ', sum(countm) / len(genderm))
print('Average Female Age: ', sum(countf) / len(genderf))
break # exit```

Related

How to track scores of list items if each item is unknown (it is users input)

I try to create a simple program for tracking students scores. This is my code, but I have no idea how to track students scores. Almost of the students are unknown and will always be different.
I am trying to detect wether the students' score is equal to 10.
name_list = []
enter_name = True
while enter_name:
name = input("Name: ")
name_list.append(name)
if name == "end":
enter_name = False
name_list = name_list[:-1]
#score = 0
#for word in name_list:
#score = int(input(f"{word} = {score}"))
#I am not sure about the last part, i think i turned to wrong direction
You should be using a dictionary keyed on student name. Values should be the student's score as an integer (because you want to compare against a constant value of 10).
As you're going to want integer input from the user, you'll need to validate it in order to avoid unwanted exceptions.
Consider this:
DB = {}
while (name := input('Enter student name: ')) != 'end':
while True:
try:
DB[name] = int(input(f'Enter score for {name}: '))
break
except ValueError:
print('Score should be an integer')
for k, v in DB.items():
print(f'{k} {"Genius" if v >= 10 else v}')
Sample:
Enter student name: Fred
Enter score for Fred: abc
Score should be an integer
Enter score for Fred: 10
Enter student name: Mick
Enter score for Mick: 5
Enter student name: end
Fred Genius
Mick 5
You should use a python dictionary:
students_scores = {}
while True:
name = input("Name: ")
if name == "end":
break
score = int(input("Score: "))
students_scores[name] = score
If you want to know whether a student has a score of 10, you can use if students_scores[student] == 10:.

Having trouble with a List-loop

Basically, you input the names and they are saved to the list. Say I input "a, b, c, d and e. After printing the list it comes out with "a, a, a, a, and a"
Then, when it asks if the student has paid or not, it doesn't matter what value you input, the name won't be moved to the designated list.
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name == raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
print "List full"
print name_list
paid_list = []
unpaid_list = []
for names in name_list:
print "Has " + name + " paid? Input y or n: "
input == raw_input()
if input == "y":
paid_list.append[input]
name_list.next
elif input == "n":
unpaid_list.append[input]
name_list.next
print "The students who have paid are", paid_list
print "The students who have not paid are", unpaid_list
Your populating loop is:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name == raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
You first assign the value received through raw_input to name.
Then, for count from 0 to 4, you check if name is equal to the input, and then, append it to name_list.
Instead of checking the equality by writing name == raw_input(...), what you want is to assign the input value into name.
Therefore, you mustn't use ==, but =.
Your loop should be:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name = raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
Now here is a more Pythonic way:
names_list = [] # there are more than one name in the list
for _ in range(5): # the loop index is not needed, so I use the anonymous underscore
name = raw_input("Enter the student's name: ")
names_list.append(name)
you can try:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5:
name = raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
print "List full"
print name_list
paid_list = []
unpaid_list = []
for names in name_list:
print "Has " + names + " paid? Input y or n: "
input = raw_input()
if input == "y":
paid_list.append[input]
elif input == "n":
unpaid_list.append[input]
Note: raw_input() is not there in python 3.x. Instead use: input() (documentation).

Making a list and retrieving it

Here is a little bit of code suposed to create a list of expenses with name and amount:
def make_list():
expense_list = []
for count in range(1, 5):
print "expense number" + str(count) + ":"
name = raw_input(' enter expense name: ')
amount = raw_input(' enter expense amount: ')
return expense_list
make_list()
What am I doing wrong? Even in interactive mode I can't seem to figure out how to get my item.
Your indentation is wrong, you never actually add anything to your list and you don't assign the returned list to anything. Also, the "magic number" (5) isn't ideal. Try:
def make_list(n):
expense_list = []
for count in range(1, n+1):
print "expense number {0}:".format(count)
name = raw_input(' enter expense name: ')
amount = raw_input(' enter expense amount: ')
expense_list.append((name, amount))
return expense_list
l = make_list(4)
print l

Python: Ask user to enter 5 different marks

The question is Write a program that asks the user to enter 5 different students and their mark out of 100. If the user tries to enter a student twice, the program should detect this and ask them to enter a unique student name (and their mark).
my program is..
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
else:
name = raw_input("Enter a unique name: ")
mark = input("Enter the mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
print dictionary
my problem is how do you loop the else: code if the user keeps entering the same name and mark?
You mix input and raw_input, that's a bad thing. Usually you use raw_input in Python 2 and input in Python 3. The quick and dirty way to solve your problem is:
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = raw_input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
else:
print("You already used that name, enter an unique name.")
print dictionary
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
name = name.strip().lower() # store name in lower case, e.g. aamir and Aamir consider duplicate
if not dictionary.get(name):
mark = input("Enter your mark out of 100: ")
dictionary[name] = mark
count += 1
else:
print "please enter unique name"
print dictionary
Store name in lowercase so that aamir and Aamir both should be consider duplicate
the duplicate check should be performed earlier than step Enter your mark to save one step for end user
i think you only need todo this:
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
print dictionary

Using a Loop to add objects to a list(python)

I'm trying to use a while loop to add objects to a list.
Here's basically what I want to do:
class x:
pass
choice = raw_input(pick what you want to do)
while(choice!=0):
if(choice==1):
Enter in info for the class:
append object to list (A)
if(choice==2):
print out length of list(A)
if(choice==0):
break
((((other options))))
I can get the object added to the list, but I am stuck at how to add multiple objects to the list in the loop.
Here is the code I have so far:
print "Welcome to the Student Management Program"
class Student:
def __init__ (self, name, age, gender, favclass):
self.name = name
self.age = age
self.gender = gender
self.fac = favclass
choice = int(raw_input("Make a Choice: " ))
while (choice !=0):
if (choice==1):
print("STUDENT")
namer = raw_input("Enter Name: ")
ager = raw_input("Enter Age: ")
sexer = raw_input("Enter Sex: ")
faver = raw_input("Enter Fav: ")
elif(choice==2):
print "TESTING LINE"
elif(choice==3):
print(len(a))
guess=int(raw_input("Make a Choice: "))
s = Student(namer, ager, sexer, faver)
a =[];
a.append(s)
raw_input("Press enter to exit")
Any help would be greatly appreciated!
The problem appears to be that you are reinitializing the list to an empty list in each iteration:
while choice != 0:
...
a = []
a.append(s)
Try moving the initialization above the loop so that it is executed only once.
a = []
while choice != 0:
...
a.append(s)
Auto-incrementing the index in a loop:
myArr[(len(myArr)+1)]={"key":"val"}

Categories