Try and Except (TypeError)
<p>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:</p>

<pre><code>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*
</code></pre>

<p>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.</p>

<p>The problem is not in your <code>try</code> and <code>except</code> but in the fact that you are using <code>try</code> and <code>except</code> at all. The code in your <code>try</code> block won't give you an error so <code>except</code> will never be triggered. You want to use an <code>if</code> statement.</p>

<p>Also, your condition only checks for <code>choice == "v"</code> because it is evaluated as <code>(choice == "v") and "g"</code>, and <code>"g"</code> is a string not of length 0, so is always "truthy" (taken as true in a Boolean context). Anything <code>and</code> True is unchanged, so only the first test has any meaning. The best way to do this test is with <code>in</code>.</p>

<p>Finally, you can and should use a <code>while</code> loop to repeat the prompt until the user enters a valid entry.</p>

<p>Putting it all together, you want something like this:</p>

<pre><code>prompt = "Enter v for validate, or g for generate &gt;"
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]
</code></pre>

<p>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 <code>input</code> stuff into a separate function, since it's called twice:</p>

<pre><code>def input1char(prompt):
    return input(prompt + " &gt;").strip().lower()[:1]
</code></pre>

<p>And then break out the while loop into its own function too:</p>

<pre><code>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
</code></pre>

<p>And then you just write:</p>

<pre><code> choice = validinput("Enter v for validate, or g for generate", "vg")
</code></pre>

python try-catch typeerror except