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
Answer from Rafael on Stack Overflow
Top answer
1 of 3
4

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
2 of 3
2

You are confused about what try/except does. try/except is used when an error is likely to be raised. No error will be raised because everything in your program is valid. Errors are raised only when there is an execution error in your code. Errors are not just raised when you need them to be.

You, however, want an error to be shown if the user does not enter a valid choice. You need to use an if/else logic instead, and print the error out yourself. And as a side note, the line choice == "v" and "g" does not test if choice is equal to 'v' or 'g'. It test if choice i equal to v and if the string 'g' is "truthy". Your estenially saying

if variable = value and True

I'm pretty sure that is not what you want. Here is how I would re-write your code.

if choice.lower() in {"v", "g"}: # if choice is 'v' or 'g'
    # do stuff
else: # otherwise
    print("Not a valid choice! Try again") # print a custom error message.
🌐
Python
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
The BaseExceptionGroup constructor returns an ExceptionGroup rather than a BaseExceptionGroup if all contained exceptions are Exception instances, so it can be used to make the selection automatic. The ExceptionGroup constructor, on the other hand, raises a TypeError if any contained exception is not an Exception subclass.
Discussions

Python 3 except TypeError not working - Stack Overflow
Please kindly note I am new to this. Your help will be appreciated. while True: user = str(input('Enter users sex:')) try: if user == 'female' or user == 'male': break except More on stackoverflow.com
🌐 stackoverflow.com
June 29, 2017
except VS except valueError: what's the difference?
It's always better to handle errors that you expect so that you don't bypass ones you don't expect. Except without an error afterwards bypasses all errors. except ValueError will only bypass a ValueError and therefore is better error handling. If a SyntaxError happens, then it won't be bypassed. This is good because it may not be expected and therefore you would not want to propagate further More on reddit.com
🌐 r/learnpython
6
1
May 19, 2020
Typecheking code inside try...except TypeError
val could be either a str or a List[int], but if it's a list it'll be caught by except TypeError More on github.com
🌐 github.com
3
November 8, 2016
What's the point of "as e" in except blocks?
You could pass e to do_something_else in case do_something_else decided what to do based on the type of error that occurred More on reddit.com
🌐 r/learnpython
29
8
October 10, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › handling-typeerror-exception-in-python
Handling TypeError Exception in Python - GeeksforGeeks
August 22, 2025 - Trying to use a variable like a string or number as if it were a function will raise a TypeError. ... To fix this error, just print the variable without parentheses. ... Python list indices must be integers or slices.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
For this purpose, exceptions have a method add_note(note) that accepts a string and adds it to the exception’s notes list. The standard traceback rendering includes all notes, in the order they were added, after the exception. >>> try: ... raise TypeError('bad type') ...
🌐
W3Schools
w3schools.com › python › ref_exception_typeerror.asp
Python TypeError Exception
You can handle the TypeError in a try...except statement, see the example below.
🌐
Real Python
realpython.com › ref › builtin-exceptions › typeerror
TypeError | Python’s Built-in Exceptions – Real Python
TypeError is a built-in exception that occurs when an operation or function is applied to an object of inappropriate type.
🌐
Medium
medium.com › @mathur.danduprolu › handling-errors-in-python-try-except-custom-exceptions-and-more-26a6aa436d20
Handling Errors in Python: Try-Except, Custom Exceptions, and More | by Mathur Danduprolu | Medium
October 30, 2024 - Keywords: Python errors, types of Python errors, SyntaxError, TypeError, ValueError, KeyError · # SyntaxError Example # print("Hello World' # TypeError Example result = "Hello" + 5 # ValueError Example num = int("abc") # IndexError Example lst = [1, 2, 3] print(lst[5]) # KeyError Example dct = {"name": "Alice"} print(dct["age"]) The try-except block is Python’s primary error-handling mechanism.
Find elsewhere
🌐
Coursera
coursera.org › tutorials › how to catch, raise, and print a python exception
How to Catch, Raise, and Print a Python Exception | Coursera
August 13, 2024 - 1 2 3 4 5 6 7 try: greeting = word1+word2 print(greeting) except TypeError: print("You can only concatenate strings to strings") except: print("Something else went wrong") ... Python attempts to execute the statements within the try clause first. If an error occurs, it skips the rest of the clause and prompts the program to follow your except clause instructions.
🌐
Rollbar
rollbar.com › home › how to fix typeerror exceptions in python
How to Fix TypeError Exceptions in Python | Rollbar
File "test.py", line 3, in <module> my_result = my_integer + my_string TypeError: unsupported operand type(s) for +: 'int' and 'str' To avoid type errors in Python, the type of an object should be checked before performing an operation.
Published: October 1, 2022
🌐
DataCamp
datacamp.com › tutorial › exception-handling-python
Exception & Error Handling in Python | Tutorial by DataCamp | DataCamp
May 29, 2026 - Yes, Python allows you to catch multiple exceptions in a single try-except block by using a tuple of exception types. For example: except (TypeError, ValueError):. This will handle either a TypeError or a ValueError in the same block.
🌐
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu › notebooks › chapter10.03-Try-Except.html
Try/Except — Python Numerical Methods
x = '6' try: if x > 3: print('X is larger than 3') except TypeError: print("Oops! x was not a valid number.
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword. Raise an error and stop the program if x is lower than 0: x = -1 if x < 0: raise Exception("Sorry, no numbers below zero") Try it Yourself » · The raise keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user. Raise a TypeError if x is not an integer: x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed") Try it Yourself » ·
Top answer
1 of 2
7

You actually don't need an exception check here. Also, your conditional statement will not raise that TypeError. Instead, simply use your conditional statement to continue your loop. This will also not require you to have to use any continue statement here either.

Furthermore, all input calls will return a string, so you do not need to cast as such. So, simply take your input without the str call:

while True:
    user = input('Enter users sex:')
    if user == 'female' or user == 'male':
        break
    else:
        print('Please enter male or female')
print('The user is:', user)

If you were putting this in to a function, you can simply return your final result once satisfied and then print the "result" of what that function returns. The following example will help illustrate this:

def get_user_gender():
    while True:
        user = str(input('Enter users sex:'))
        if user == 'female' or user == 'male':
            break
        else:
            print('Please enter male or female')
    return 'The user is: {}'.format(user)


user_gender = get_user_gender()
print(user_gender)

Small note, you will notice I introduced the format string method. It makes manipulating strings a bit easier getting in to the habit with dealing with your string manipulation/formatting in this way.

2 of 2
2

input() returns a string in Python 3. Calling str on it leaves it as it is, so it will never raise an exception.

You could get an error if you tried to do something like:

number = int(input("enter a number: "))

enter a number: abc
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-ec0ea39b1c6c> in <module>()
----> 1 number = int(input("enter a number: "))

ValueError: invalid literal for int() with base 10: 'abc'

because the string 'abc' can't be converted to an integer (in base 10, at least...)

🌐
Readthedocs
portingguide.readthedocs.io › en › latest › exceptions.html
Exceptions — Conservative Python 3 Porting Guide 1.0 documentation
In Python 2, the syntax for catching exceptions was except ExceptionType:, or except ExceptionType, target: when the exception object is desired. ExceptionType can be a tuple, as in, for example, except (TypeError, ValueError):.
🌐
freeCodeCamp
freecodecamp.org › news › python-try-and-except-statements-how-to-handle-exceptions-in-python
Python Try and Except Statements – How to Handle Exceptions in Python
September 23, 2021 - Otherwise, the except block corresponding to the TypeError is triggered, notifying the user that the argument is of invalid type.
🌐
GitHub
github.com › python › mypy › issues › 2420
Typecheking code inside try...except TypeError · Issue #2420 · python/mypy
November 8, 2016 - here's an example: from typing import Union,List def fn(val: Union[str,List[int]]) -> int: try: res = int(val) except (ValueError,TypeError): res = 0 return res print(fn("123"),fn([])) val could be either a str or a List[int], but if it'...
Author: python
🌐
PythonForBeginners.com
pythonforbeginners.com › home › typeerror in python
TypeError in Python - PythonForBeginners.com
December 28, 2022 - Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module> myResult = list1 + list2 TypeError: can only concatenate list (not "tuple") to list · Looking at these examples, we can say that TypeError is an exception that is raised by the python interpreter if the data types of different objects in an operation are not compatible and hence inappropriate.