Search code examples
pythonpython-3.xinputwhile-loopalphanumeric

Input does not check for first loop when 3rd loop is executed? py3


I am getting user name input in python3. I have used 3 while loops for strings only, 12 characters limit and less than 3 characters. So name must be alphabets and a genuine name. When I run program and input a wrong name it keeps asking to correct name but when I give a direct correct input of third loop than it does not check for first two loops. I mean when I input keep entering more than 12 characters and suddenly give input of random name with numbers it just accepts the input but does not execute first loop and program just ends in terminal window. here's my code:

print('lets see what it does')

f_name=input('Enter your first name:')
while f_name.isalpha()==False:
    print('Please Enter Alphabets only')
    f_name=input('Please reenter name:')
while len(f_name)>12:
    print('Name exceeds character limit.')
    f_name=input('Please reenter name:')
while len(f_name)<3:
    print('Name must be atlest three characters long')
    f_name=input('Please ReEnter Name:')

and here is the output:

lets see what it does
Enter your first name:ppp000
Please Enter Alphabets only
Please reenter name:pppppppppppppppp8
Please Enter Alphabets only
Please reenter name:ppppppppppppppp8
Please Enter Alphabets only
Please reenter name:pp9
Please Enter Alphabets only
Please reenter name:pp00
Please Enter Alphabets only
Please reenter name:pppppppppp8
Please Enter Alphabets only
Please reenter name:jijija8
Please Enter Alphabets only
Please reenter name:ijajsidaosdasdasdasd
Name exceeds character limit.
Please reenter name:ppp0```

Solution

  • I would recommend using a function to validate a name. Then you can use the := operator to define f_name.

    def is_name_valid(name):
        return (
                name.isalpha() and
                12 >= len(name) >= 3
        )
    
    
    def main():
        while not is_name_valid(f_name := input('Enter your first name: ')):
            print("Name is invalid")
        print(f_name)
    
    

    If you need to prompt why the name is invalid, you can use different return values: 0 for valid, 1 for .isalpha() etc... For good error handling, you may want to use enums or consts.