Try and Except (TypeError)

AntsOfTheSky picture AntsOfTheSky · Oct 19, 2016 · Viewed 17.4k times · Source

What I'm trying to do is create a menu-style start in my program that let's the user choose whether they want to validate a code or generate one. The code looks like this:

choice = input("enter v for validate, or enter g for generate").lower()

try:
   choice == "v" and "g"

except TypeError:
   print("Not a valid choice! Try again")
   restartCode()    *#pre-defined function, d/w about this*

So I would like my program to output that print statement and do that defined function when the user inputs something other than "v" or "g" (not including when they enter capitalised versions of those characters). There is something wrong with my try and except function, but whenever the user inputs something other than those 2 characters the code just ends.

Answer

Rafael picture Rafael · Oct 19, 2016

Try.

choice = input("enter v for validate, or enter g for generate").lower()

if (choice == "v") or (choice == "g"):
    #do something
else :
   print("Not a valid choice! Try again")
   restartCode()    #pre-defined function, d/w about this*

However, if you really want to stick with try/except you can store the desired inputs, and compare against them. The error will be a KeyError instead of a TypeError.

choice = input("enter v for validate, or enter g for generate").lower()
valid_choices = {'v':1, 'g':1}

try:
    valid_choices[choice]
    #do something

except:
    KeyError
    print("Not a valid choice! Try again")
    restartCode()   #pre-defined function, d/w about this