我不能让数据保留在字典中,它会不断更新
I can't let the data to remain in the dictionary, it keeps updating instead
我给自己买了一本 python 书。目前,在书中,我正在学习字典。这本书给了我一个关于字典的练习。就是这个问题。
"创建一个程序,将学生的姓名与他的 class 成绩配对。用户应该能够根据需要输入尽可能多的学生,然后打印出所有学生的姓名和成绩。输出应该看起来像这样:
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()
我稍微修改了代码以测试字典。我也用 python 2
你只犯了一个错误 是当你将数据附加到字典时:
studentmarks = {name: grade}
应该是这样的:
studentmarks[name] = grade
每次到达此行时,您都在覆盖字典:
studentmarks = {name: grade}
应该是这样的:
studentmarks[name] = grade
我给自己买了一本 python 书。目前,在书中,我正在学习字典。这本书给了我一个关于字典的练习。就是这个问题。
"创建一个程序,将学生的姓名与他的 class 成绩配对。用户应该能够根据需要输入尽可能多的学生,然后打印出所有学生的姓名和成绩。输出应该看起来像这样:
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()
我稍微修改了代码以测试字典。我也用 python 2
你只犯了一个错误 是当你将数据附加到字典时:
studentmarks = {name: grade}
应该是这样的:
studentmarks[name] = grade
每次到达此行时,您都在覆盖字典:
studentmarks = {name: grade}
应该是这样的:
studentmarks[name] = grade