2

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

martineau
  • 119,623
  • 25
  • 170
  • 301
Pedro Henrique
  • 181
  • 3
  • 11
  • 7
    `'MF'` does contain an empty string - three of them, in fact. Your test would also allow `'MF'` to be entered, as you aren't checking the substring length at all. Try `sex not in ('M', 'F')` to allow only those two particular inputs. – jasonharper May 10 '20 at 03:06
  • @jasonharper beat me to it; I missed this at first due to battle fatigue. Yes, the empty string is included in *any* string. – Prune May 10 '20 at 03:08
  • Thank you very much, helped a lot. I'm really new into programming, but liking it so much – Pedro Henrique May 10 '20 at 03:10

1 Answers1

4

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!!!')
JolonB
  • 415
  • 5
  • 25