extramundane extramundane - 26 days ago 5
Python Question

While-Loop Troubles

I have to make a gradebook program for my CS class, and I'm having problems with my while-loop (bear with me, I'm a beginner). I am trying to set it up so that a teacher will be able to add an infinite amount of students to their gradebook. We're also saving it to a text file. For some reason after I enter one name, the loop doesn't continue, it just skips to the other if statement below it. Thanks for your help.

#input students

studentnames=open("studentnames.txt","w")
stu = input ("Would you like to input new students? (Yes or No) ")
if stu == 'Yes' or 'yes':
while True:
add = input ("Please enter the names you would like to add to your registry. (Type stop when you're finished.) ")
studentnames.writelines(add)

if add == 'Stop' or 'stop':
break

if stu == 'No' or 'no':
print ("Okay.")


studentnames.close()

Answer

Ok. The problem is that python understands line

if add == 'Stop' or 'stop':

as

if (add == 'Stop') or ('stop'):

So. Even if add == 'Stop' is False, python casts 'stop' to True, so it executes if statement anyway. So use if add.lower() == 'stop': instead. (same in if stu == 'No' or 'no':

Comments