byenwomolo
byenwomolo

Reputation: 131

Python 3 except TypeError not working

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 TypeError:
        print('Please enter male or female')
    continue
print('The user is:',user)

I do not understand when an integer is entered the

except TypeError:
    print('Please enter male or female')

does not print('Please enter male or female') and ask the user for input.

Upvotes: 2

Views: 1924

Answers (2)

idjaw
idjaw

Reputation: 26570

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.

Upvotes: 7

Thierry Lathuille
Thierry Lathuille

Reputation: 24233

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

Upvotes: 2

Related Questions