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
238 views
in Technique[技术] by (71.8m points)

Python: How do I satisfy either or of two completely different conditions in a while loop

I wanted to have a while loop that takes in a string of either only numbers, the string "value", or string "v". I tried doing :

num = input('type a number, "value", or "v". ')
while num.lower() not in ["value", "v"] or num.isdigit() != True:
    num = input("Can only input numbers or 'value' or 'v'. please try again ")
if num.lower() == "value" or num.lower() == "v":
    print("Great you want a value!")
elif num.isdigit() == True:
    print(f"Your number is {num}")

This does not work because it goes into an infinite loop of asking me to input again. I believe it's because the while loop wants to satisfy both conditions but can't. Any way to retype the while conditions or suggestions on a different approach?

question from:https://stackoverflow.com/questions/65876521/python-how-do-i-satisfy-either-or-of-two-completely-different-conditions-in-a-w

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

1 Answer

0 votes
by (71.8m points)

You don't need to prompt for it twice, and you needed an "and" not an "or". Try this:

num = ''
while num.lower() not in ["value", "v"] and num.isdigit() != True:
    num = input("Can only input numbers or 'value' or 'v'. please try again ")
if num.lower() == "value" or num.lower() == "v":
    print("Great you want a value!")
elif num.isdigit() == True:
    print(f"Your number is {num}")

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

...