当前使用3.8.1。
[我想知道如何像下面的示例那样进行while True:
循环,但是使用用户输入的数字而不是单词(例如,等于或小于100的任何数字将打印出不同的内容。我ve看过这个网站,但对于与我类似的问题,我听不懂答案。
while True:
question = input("Would you like to save?")
if question.lower() in ('yes'):
print("Saved!")
print("Select another option to continue.")
break
if question.lower() in ('no'):
print ("Select another option to continue.")
break
else:
print("Invalid answer. Please try yes or no.")
while True:
# get user input:
user_input = input("Would you like to save? ")
# convert to int:
number = int(user_input)
if number <= 100:
print("Saved!")
print("Select another option to continue.")
break
elif number > 100:
print ("Select another option to continue.")
break
else:
print("Invalid answer. Please try yes or no.")
while True:
input_val = input("Enter a #?")
try:
num=int(input_val)
except ValueError:
print("You have entered an invalid number. please try again")
continue
if num == 1:
print("bla bla")
elif num ==2:
print("bla bla 2")
else:
...
input
接受用户的输入并输出一个字符串。要对数字进行处理,请检查字符串是否为数字,将其转换为int并做任何您想做的事情while True:
answer = input("How many dogs do you have?")
if answer.isnumeric():
num_dogs = int(answer)
else:
print("Please input a valid number")
可以这样做:
while True:
number = input("Enter a number?")
if int(number) in list(n for n in range(100)):
print("lower!")
elif int(number) in [100]:
print ("exact")
else:
print("higher")