Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try and Except (TypeError)

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.

like image 566
AntsOfTheSky Avatar asked Mar 11 '23 21:03

AntsOfTheSky


1 Answers

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
like image 124
Rafael Avatar answered Mar 15 '23 16:03

Rafael