Reputation: 541
I am asking for an input from the user and it has to be a single character alphabet.
I tried this code.
ask = ''
while len(ask) != 1 and ask.isalpha() != True:
ask = input(message).upper()
But this accepts any single number digit to break out of the while loop. I don't understand why.
I checked the ask.isalpha()
on that single number and that returns False. So why does it break out of the loop.
Sorry for this question. This is very naïve but I couldn't find an answer.
Thank you.
Edit: Added the whole code.
Upvotes: 0
Views: 508
Reputation: 1
There is different way to do it
# if you want user to enter upper case
while True:
ask = input('message: ')
if len(ask) == 1 and ask.isalpha() == True and ask.isupper() == True:
break
# if you want to convert input to upper
while True:
ask = (input('message: ')).upper()
if len(ask) == 1 and ask.isalpha() == True:
break
is this case all your condition are satisfied,
Upvotes: 0
Reputation: 71560
You need an or
operation and not and
to achieve what you want. Also, you need to take user input first time before entering the while
loop.
So your code should be:
ask = input(message).upper()
while len(ask) != 1 or ask.isalpha() != True:
ask = input(message).upper()
Upvotes: 1
Reputation: 3
You are using !=
which stand for not equal to so when you enter 1 digit number condition for while
loop doesn't match so code stops. You should use ==
instead of !=
.
Upvotes: 0