简体   繁体   中英

Python: user input exception handling with Str

     while True:
        first_name = input('Please enter your first name:\n')
        last_name = input('Please enter your last name:\n')
        try:
             firstn = str(first_name)
             lastn = str(last_name)
        except ValueError:

            print('did not enter str')
            continue
        else:
            return firstn
            return lastn

I'm trying to use exception handling with my code. I want to check whether or not the user has inputed the correct string value for first and last name. users cannot input numbers for their first and last names. my code seems to ignore the Value error if I use numbers for usernames.

Your issue is in the understanding of what you code does. When you do

first_name = input('Please enter your first name:\n')

then first_name is already a string representing the exact user input. So you writing

firstn = str(first_name)

has actually no real effect, except copying first_name . The string might be something like "12345" but is still a valid string. What you want is probably to check if the string only contains alphabetic characters, which can be achieved by calling .isalpha() :

if not first_name.isalpha():
    raise ValueError

Not directly related to your question, but also worth noting:

return firstn
return lastn

will also not have the desired effect, since only the first return will be executed, resulting in only firstn to be returned. You probably want:

return firstn, lastn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM