Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop conditional statements based on specific user input in Python?

Tags:

python

For example, in this sample code,

greeting = input("What's your favorite cheese?")
if greeting == "cheddar":
    print("Mine too!")

elif greeting == "bleu cheese":
    print("Gross!")

elif greeting == "parmesan":
    print("Delicious!")

else:
    cheese = input("That's not a cheese, try again!")
    cheese == greeting

if I input "Mozzarella" as 'greeting', I would like it to prompt me with "That's not a cheese" and also let me re-input a value for 'greeting' until cheddar, bleu cheese, or parmesan is entered, if that makes any sense. I have a larger program I am working on for class that involves multiple conditional statements nested within each other, and for each 'set' of statements I'd like to be able to print an error message when the user inputs an invalid entry and allow them to try again without having to restart the program.

like image 398
kuroizora Avatar asked Mar 13 '26 11:03

kuroizora


1 Answers

Try the following

greeting = input("What's your favorite cheese?") #Get input
while greeting not in ['cheddar', 'blue cheese', 'parmesan']: #Check to see if the input is not a cheese
    greeting = input("That's not a cheese, try again!")
else: #If it is a cheese, proceed
    if greeting == "cheddar":
        print("Mine too!")

    elif greeting == "bleu cheese":
        print("Gross!")

    elif greeting == "parmesan":
        print("Delicious!")

    else:
        cheese = input("That's not a cheese, try again!")

What's your favorite cheese? peanut butter
That's not a cheese, try again! ketchup
That's not a cheese, try again! parmesan
Delicious!
like image 124
A.J. Uppal Avatar answered Mar 15 '26 00:03

A.J. Uppal



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!