Python while 循环/范围
我需要从用户那里获取一个数字,然后检查这个数字是否在一个低值和高值之间。如果在这个范围内,就返回这个数字;如果不在范围内,就一直让用户输入,直到输入的数字在范围内。我其实不太确定该怎么做,但我觉得我已经有了一部分的代码。我最担心的是这一行“while question != low <= question <= high:”,我觉得这一行可能有问题。
def ask_number(question, low, high):
question = int(raw_input("Enter a number within the range: "))
question = ""
while question != low <= question <= high:
question = int(raw_input("Enter a number within the range: "))
4 个回答
0
def ask_number(low, high):
while True:
number = int(raw_input('Enter a number within the range: '))
if number in xrange(low, high + 1):
return number
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
3
你的 while 循环写法可以更清晰一点,想象成这样:“我想一直问用户答案,只要他们的答案小于最低值或大于最高值。” 如果直接用 Python 表达,这样写就可以了:
while question < low or question > high:
另外,不要把 ""
赋值给 question
,因为这样会覆盖用户第一次的回答。如果他们第一次就答对了,还是会被问一次。简单来说,你应该去掉这一行:
question = ""
你的最终代码应该像这样:
def ask_number(low, high):
assert low < high
question = int(raw_input("Enter a number within the range: "))
while question < low or question > high:
question = int(raw_input("Enter a number within the range: "))
return question
print(ask_number(5,20))
3
在这种情况下,最简单的解决办法是在 while
循环中使用 True
作为条件,然后在循环内部加一个 if
语句,如果数字符合要求就跳出循环:
def ask_number(low, high):
while True:
try:
number = int(raw_input("Enter a number within the range: "))
except ValueError:
continue
if low <= number <= high:
return number
我还添加了一个 try
/except
语句,这样如果用户输入了无法转换成数字的字符串,程序就不会崩溃。