kuroizora
kuroizora

Reputation: 33

How to loop conditional statements based on specific user input in 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.

Upvotes: 3

Views: 337

Answers (3)

A.J. Uppal
A.J. Uppal

Reputation: 19264

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!

Upvotes: 3

MikeVaughan
MikeVaughan

Reputation: 1501

Build a dict with your responses to each cheese, with the names of the cheeses as the keys. The use a while loop.

cheeses = {'bleu cheese':'Gross!','cheddar':'Mine Too!','parmesan':'Delicous!'}

greeting = input("What's your favorite cheese?")

while greeting not in cheeses:
    print "That's not a Cheese! Try Again!"
    greeting = input("Whats your favorite cheese?")


print cheeses[greeting]

Upvotes: 2

dursk
dursk

Reputation: 4445

greeting = ''
while greeting not in ['cheddar', 'blue cheese', 'parmesan']:
    greeting = input("That's not a cheese, try again!")

Upvotes: 3

Related Questions