Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop to check for valid user input? [duplicate]

Python newbie here so sorry for what I'm sure is a stupid question, but I can't seem to solve the following challenge in a tutorial that is asking me to use a while loop to check for valid user input.

(using Python2.7)

Here's my code, but it's not working properly:

choice = raw_input('Enjoying the course? (y/n)')
student_surveyPromptOn = True
while student_surveyPromptOn:
    if choice != raw_input('Enjoying the course? (y/n)'):
        print("Sorry, I didn't catch that. Enter again: ")
    else:
        student_surveyPromptOn = False 

The above prints out to the console:

Enjoying the course? (y/n) y
Enjoying the course? (y/n) n
Sorry, I didn't catch that. Enter again: 
Enjoying the course? (y/n) x
Sorry, I didn't catch that. Enter again: 
Enjoying the course? (y/n)  

Which obviously isn't correct — the loop should end when the user enters either 'y' or 'n' but I'm not sure how to do this. What am I doing wrong here?

Note: the challenge requires me to use both the != operator and the loop_condition

like image 464
AdjunctProfessorFalcon Avatar asked Aug 07 '26 17:08

AdjunctProfessorFalcon


1 Answers

You can use the condition

while choice not in ('y', 'n'):
    choice = raw_input('Enjoying the course? (y/n)')
    if not choice:
        print("Sorry, I didn't catch that. Enter again: ")
like image 53
Cory Kramer Avatar answered Aug 10 '26 07:08

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!