检查数字是否在python中的某个范围内(带循环)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13921707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if numbers are in a certain range in python (with a loop)?
提问by Average kid
Here's my code:
这是我的代码:
total = int(input("How many students are there "))
print("Please enter their scores, between 1 - 100")
myList = []
for i in range (total):
n = int(input("Enter a test score >> "))
myList.append(n)
Basically I'm writing a program to calculate test scores but first the user has to enter the scores which are between 0 - 100.
基本上我正在编写一个程序来计算测试分数,但首先用户必须输入 0 - 100 之间的分数。
If the user enters a test score out of that range, I want the program to tell the user to rewrite that number. I don't want the program to just end with a error. How can I do that?
如果用户输入的测试分数超出该范围,我希望程序告诉用户重写该数字。我不希望程序以错误结束。我怎样才能做到这一点?
回答by NPE
while True:
n = int(input("enter a number between 0 and 100: "))
if 0 <= n <= 100:
break
print('try again')
Just like the code in your question, this will work both in Python 2.x and 3.x.
就像您问题中的代码一样,这将适用于 Python 2.x 和 3.x。
回答by abarnert
First, you have to know how to check whether a value is in a range. That's easy:
首先,您必须知道如何检查一个值是否在一个范围内。这很容易:
if n in range(0, 101):
Almost a direct translation from English. (This is only a good solution for Python 3.0 or later, but you're clearly using Python 3.)
几乎是直接从英语翻译过来的。(这只是 Python 3.0 或更高版本的一个很好的解决方案,但您显然使用的是 Python 3。)
Next, if you want to make them keep trying until they enter something valid, just do it in a loop:
接下来,如果你想让他们继续尝试直到他们输入有效的东西,只需在循环中进行:
for i in range(total):
while True:
n = int(input("Enter a test score >> "))
if n in range(0, 101):
break
myList.append(n)
Again, almost a direct translation from English.
同样,几乎是从英语直接翻译。
But it might be much clearer if you break this out into a separate function:
但是如果你把它分解成一个单独的函数可能会更清楚:
def getTestScore():
while True:
n = int(input("Enter a test score >> "))
if n in range(0, 101):
return n
for i in range(total):
n = getTestScore()
myList.append(n)
As f p points out, the program will still "just end with a error" if they type something that isn't an integer, such as "A+". Handling that is a bit trickier. The intfunction will raise a ValueErrorif you give it a string that isn't a valid representation of an integer. So:
正如 fp 指出的那样,如果他们输入的不是整数,例如“A+”,程序仍将“以错误结束”。处理起来有点棘手。如果您给它一个不是整数的有效表示的字符串,该int函数将引发 a ValueError。所以:
def getTestScore():
while True:
try:
n = int(input("Enter a test score >> "))
except ValueError:
pass
else:
if n in range(0, 101):
return n
回答by millimoose
You can use a helper function like:
您可以使用辅助函数,例如:
def input_number(min, max):
while True:
n = input("Please enter a number between {} and {}:".format(min, max))
n = int(n)
if (min <= n <= max):
return n
else:
print("Bzzt! Wrong.")

