我有一個關於這個代碼的問題:這個Python列表代碼有什麼問題?
menu = ""
student = []
print ("What would you like to do?")
print ("\t[1] Show full gradebook")
print ("\t[2] Add Student")
print ("\t[3] Remove Student")
print ("\t[4] Modify Student Information")
print ("\t[5] Display Highest Grade")
print ("\t[6] Display Lowest Grade")
print ("\t[7] Quit")
# loop until the user decides to quit
while menu != 7:
menu = int(input("Enter selection [1-7]"))
if menu == 1:
print("Name\tGrade")
# loop through all students
for s in student:
print(s[0]+"\t"+str(s[1]))
elif menu == 2:
# prompt user for student name
sname = input("Student Name?")
# prompt user for student grade
sgrade = int(input("Student Grade?"))
# append student information to list
student.append([sname, sgrade])
elif menu == 3:
sname = input("Student to remove?")
try:
student.remove([sname, sgrade])
except:
if sname not in student:
print("Not in table.")
elif menu == 4:
sname = input("Student to modify?")
for s in student:
print(s[0]+"\t"+str(s[1]))
try:
student.remove([sname, sgrade])
sname = input("Name: (press Enter to keep original value)")
sgrade = int(input("Grade: (press Enter to keep original value)"))
student.append([sname, sgrade])
except:
if sname not in student:
print("Not in table.")
elif menu == 5:
try:
print(sname + " had the highest score in the class: " + str(sgrade))
except:
pass
elif menu == 6:
try:
print(sname + " had the lowest score in the class: " + str(sgrade))
except:
pass
elif menu >= 8:
print("Invalid selection.")
print ("Terminating program... Goodbye!")
每次我嘗試選擇3至6與多個學生,它會做它爲學生在列表的底部。另外,當我修改學生信息時,我想知道如何保留某個學生的原名或成績。
「做」 - 做什麼? – DyZ
如果您將每個操作移至不同的功能,您將看到問題。並且將while循環移動到主函數。您正在重複使用前一次迭代中的'sgrade'變量 – balki