I got myself a python book. Currently, in the book, I am learning about dictionaries. The book gave me an exercise about dictionaries. This is the question.
"Create a program that pairs student's name to his class grade. The user should be able to enter as many students as needed and then get a printout of all students' names and grades. The output should look like this:
Please give me the name of the student (q to quit): [input]
Please give me their grade: [input]
[And so on...]
Please give me the name of the student (q to quit): [input]: q
Okay, printing grades!
Student Grade
Student1 A
Student2 B
[And so on...] "
def student():
studentmarks = {}
while True:
name = raw_input("Please give me the name of the student ('q' to quit):")
if name == "q":
break
elif name.isalpha() == True:
grade = raw_input("Please give me their grade ('q' to quit):")
if grade == "q":
break
elif grade.isalpha() == True:
print "Grade is a number! Please try again"
continue
elif grade.isdigit() == True:
studentmarks = {name: grade}
else:
print "Error, please try again"
continue
else:
print "Please try again. {} is not the right input".format(name)
continue
print studentmarks
continue
student()
I modified the code a bit to test the dictionary. I also use python 2
CodePudding user response:
you made only one mistake witch is when you append the data to dictionary:
studentmarks = {name: grade}
it should be like this :
studentmarks[name] = grade
CodePudding user response:
You're overwriting the dictionary every time you get to this line:
studentmarks = {name: grade}
It should be like this:
studentmarks[name] = grade