Search code examples
pythonfunctionloopsvalidationisalpha

Is there a way to simplify isalpha, len function, in a while loop?


I'm a very new programmer. Just starting out in Python. Essentially I have a to write a program that accepts username input, with some validation. The username has to be between 5-10 alphabetical characters. I'm getting the code to test for the length of the string, but I'm not getting it to test for alphabetical characters. What am I doing wrong?

correct = True
while correct:
    username = input('Enter a username that has only alphabetical characters and is between 5 and 10 characters long:')
    if username.isalpha:
        while len(username) < 5:
            print('Invalid username! Please try again.')
            username = input('Enter a username that has only alphabetical characters' +
                             ' and is between 5 and 10 characters long:')
        if username.isalpha:
            while len(username) > 10:
                print('Invalid username! Please try again.')
                username = input('Enter a username that has only alphabetical characters' +
                                 ' and is between 5 and 10 characters long:')
            correct = False
else:
    print('Username accepted.')

Solution

  • As it is mentioned in the comment section, you missed the parenthesis () of isalpha.
    I also suggest to edit the code like this:

    while True:
        username = input('Enter a username that has only alphabetical characters and is between 5 and 10 characters long:')
        if username.isalpha() and 5 <= len(username) <= 10:
            print('Username accepted.')
            break
        else:
            print('Invalid username! Please try again.')