Reputation: 65
So I have this code so that I can add some students to a list, but I also have a line where if they enter a blank string it takes the user back to the menu. However, when I enter the blank string it also adds that to the list of students. How can I change that?
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")
Output:
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', '']
Another problem I have is that after I enter two names of students, it prints the list out before the user enters a blank string.
How can I fix this? Thanks.
Upvotes: 0
Views: 50
Reputation: 1466
You should add a line to check if the line that contains the student name was blank, and in such case, return to the menu by exiting the while loop
Also, the first time that you ask for a student name is actually not used. I would delete the two lines on top of the while and instead, just assign a non-blank value to enterStudent. So I would change this:
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)
To this:
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)
Upvotes: 0
Reputation: 781721
Your loop isn't testing whether the student name is blank until it goes back to the top of the loop, which is after it adds the entry the list. Try:
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)
Upvotes: 1