pythoninputverifier

Why it ignores my while condition when I input an void string ('nothing here')?


I have this code:

sex = str(input('type sex:')).upper()

while sex not in 'MF':
    sex = str(input('try again: ')).upper()
print('Done!!!')

It works fine as a validation thing when I try to input almost anything, but when it's '', it just jumps over my while loop. I've tried initializing the sex string in the beginning, but it didn't help :c


Solution

  • As jasonharper said, 'MF' contains 3 empty strings. To fix it, you could change the code to:

    while sex not in ('M', 'F'):
        sex = str(input('try again: ')).upper()
    print('Done!!!')
    

    Or if you really want to use 'MF', you could have an additional check for an empty string in the while loop:

    while not sex and sex not in 'MF':
        sex = str(input('try again: ')).upper()
    print('Done!!!')