The problem is not in your try
and except
but in the fact that you are using try
and except
at all. The code in your try
block won't give you an error so except
will never be triggered. You want to use an if
statement.
Also, your condition only checks for choice == "v"
because it is evaluated as (choice == "v") and "g"
, and "g"
is a string not of length 0, so is always "truthy" (taken as true in a Boolean context). Anything and
True is unchanged, so only the first test has any meaning. The best way to do this test is with in
.
Finally, you can and should use a while
loop to repeat the prompt until the user enters a valid entry.
Putting it all together, you want something like this:
prompt = "Enter v for validate, or g for generate >"
choice = input(prompt).strip().lower()[:1] # take at most 1 character
while choice not in ("v", "g"):
print("Not a valid choice! Try again.")
choice = input(prompt).strip().lower()[:1]
If you think of how you might generalize the code to use it again (as you probably will in the rest of your script), it's easy and useful to do so. First, you can break out the input
stuff into a separate function, since it's called twice:
def input1char(prompt):
return input(prompt + " >").strip().lower()[:1]
And then break out the while loop into its own function too:
def validinput(prompt, options):
letters = tuple(options)
choice = input1char(prompt)
while choice not in options:
print("'%s' is not a valid choice! Try again." % choice)
choice = input1char(prompt)
return choice
And then you just write:
choice = validinput("Enter v for validate, or g for generate", "vg")