-1

I'm new to Python, with a bit of background in C. I'd like to set up a while loop with try - except - else construction. I have successfully done this when trying to verify a data type (using except: ValueError), for instance prompting the user for an integer. However for this program, the the user inputs a string and the program needs to check that string against a list of strings, and if it's not in there, ask the user again. My code so far runs but regardless of the user's input, the loop breaks. Here it is now:

senses = ["touch", "smell", "sight", "hearing", "taste"]


while True:
    try:
        choice = input("What is your favorite sense? ")

    except: 
        if choice not in senses:
            print("Sorry, I don't think that's a sense")
            #try again, return to start of loop
            continue 
    else:
        break 

Originally my code looked like this and it worked but there is the issue of redundancy with the input method:

senses = ["touch", "smell", "sight", "hearing", "taste"]
choice = input("What is your favorite of the 5 human senses:")

while choice not in senses:

    choice =input("What is your favorite of the 5 human senses")
Mr. Cat
  • 27
  • 6
  • 2
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Patrick Artner Jan 17 '19 at 19:50

2 Answers2

1

A matter of personal preference / problem suitability, but I would tend to use something like this

senses = ["touch", "smell", "sight", "hearing", "taste"]
choice = ""

while choice not in senses:
    choice =input("What is your favorite of the 5 human senses")

This initializes choice as something not in senses, thus forcing the first loop

CJC
  • 76
  • 5
1

I'd write that like:

senses = {"touch", "smell", "sight", "hearing", "taste"}

while True:
    choice = input("What is your favorite of the 5 human senses? ")
    if choice in senses:
        break

This way you're only asking the question in one place. while True means "do this forever", and break stops the loop once the condition is met.

Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65