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.
🌐
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...)

🌐
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.
🌐
LabEx
labex.io › tutorials › python-how-to-handle-typeerror-exception-in-python-398017
How to handle TypeError exception in Python | LabEx
One of the most effective ways to handle TypeError exceptions is to perform proactive type checking before executing potentially problematic operations. This can be done in several ways: Use type annotations: Leverage Python's type annotation feature to specify the expected types of function parameters and return values.
🌐
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.
🌐
Pronod's Blog
data-intelligence.hashnode.dev › handling-typeerror-in-python-guide
Understanding and Fixing Python TypeErrors - Pronod's Blog
September 13, 2024 - Handle TypeError gracefully using try-except blocks, validating user input, and providing clear error messages.