所以我有这个代码,以便我可以将一些学生添加到列表中,但我也有一行,如果他们输入一个空白字符串,它会将用户带回菜单。但是,当我输入空白字符串时,它还会将其添加到学生列表中。我怎么能改变它?
students = []
ans = True
while ans:
print ("""
a.Add new students
b.Show student list
c.Delete a student
d.Exit
""")
ans = input("What would you like to do? ")
if ans == "a":
enterStudent = input ("Enter a new student name:")
students = [enterStudent]
while enterStudent != "": #loop to enter multiple student names
enterStudent = input ("Enter a new student name:")
students.append (enterStudent)
print ("The list now contains the students :",students)
elif ans == "b":
print("\n The current student list is:")
print (*students,sep='\n')
elif ans == "c": #delete a student from the list.
removeStudent = input ("Enter a student name to delete:")
students.remove (removeStudent)
elif ans == "d":
print("\n Goodbye")
elif ans != "":
print("\n Try again")
输出:
What would you like to do? a
Enter a new student name:Bob Bob
Enter a new student name:Bob Bob
The list now contains the students : ['Bob Bob', 'Bob Bob']
Enter a new student name:
The list now contains the students : ['Bob Bob', 'Bob Bob', '']
我遇到的另一个问题是,在输入两个学生名字后,它会在用户输入空白字符串之前打印出列表。
我该如何解决这个问题?感谢。
答案 0 :(得分:1)
你的循环没有测试学生名称是否为空,直到它回到循环的顶部,这是在它添加条目列表之后。尝试:
students = []
while True:
enterStudent = input("Enter a new student name:")
if not enterStudent:
break
students.append(enterStudent)
print ("The list now contains the students :",students)
答案 1 :(得分:0)
你应该添加一行来检查包含学生姓名的行是否为空白,在这种情况下,通过退出while循环返回菜单
此外,您第一次要求学生姓名实际上并未使用。我会删除while上面的两行,而只是为enterStudent指定一个非空值。所以我会改变这个:
enterStudent = input ("Enter a new student name:")
students = [enterStudent]
while enterStudent != "": #loop to enter multiple student names
enterStudent = input ("Enter a new student name:")
students.append (enterStudent)
print ("The list now contains the students :",students)
对此:
students = []
enterStudent = "goIntoWhile"
while enterStudent != "": #loop to enter multiple student names
enterStudent = input ("Enter a new student name:")
if enterStudent == "":
break
students.append (enterStudent)
print ("The list now contains the students :",students)