Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
71 views
in Technique[技术] by (71.8m points)

python - While Loop doesn't recognize multiple conditions

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.

question from:https://stackoverflow.com/questions/65840466/while-loop-doesnt-recognize-multiple-conditions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...