3

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.

2
  • 2
    Look at the while loop. Commented Mar 10, 2015 at 19:50
  • 2
    Also you might want to construct a dict with valid cheeses and your responses. It would make the code easier to manage. Commented Mar 10, 2015 at 19:52

3 Answers 3

3

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!
Sign up to request clarification or add additional context in comments.

2 Comments

I still think using a dictionary is a better idea for this. But this definitely works.
@MikeVaughan true enough, it saves some lines of code, but I don't want to change the OP's code unless called for.
3
greeting = ''
while greeting not in ['cheddar', 'blue cheese', 'parmesan']:
    greeting = input("That's not a cheese, try again!")

Comments

2

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]

1 Comment

this is better that recursive if-else

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.