将用户输入限制在 Python 中的某个范围内
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19821273/
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
Limiting user input to a range in Python
提问by Kraig Clubb
In the code below you'll see it asking for a 'shift' value. My problem is that I want to limit the input to 1 through 26.
在下面的代码中,您会看到它要求一个“移位”值。我的问题是我想将输入限制为 1 到 26。
For char in sentence:
if char in validLetters or char in space: #checks for
newString += char #useable characters
shift = input("Please enter your shift (1 - 26) : ")#choose a shift
resulta = []
for ch in newString:
x = ord(ch) #determines placement in ASCII code
x = x+shift #applies the shift from the Cipher
resulta.append(chr(x if 97 <= x <= 122 else 96+x%122) if ch != \
' ' else ch) # This line finds the character by its ASCII code
How do I do this easily?
我该如何轻松做到这一点?
采纳答案by thegrinner
Use a while
loop to keep asking them for input until you receive something you consider valid:
使用while
循环不断询问他们的输入,直到您收到您认为有效的内容:
shift = 0
while 1 > shift or 26 < shift:
try:
# Swap raw_input for input in Python 3.x
shift = int(raw_input("Please enter your shift (1 - 26) : "))
except ValueError:
# Remember, print is a function in 3.x
print "That wasn't an integer :("
You'll also want to have a try-except
block around the int()
call, in case you get a ValueError
(if they type a
for example).
您还需要try-except
在int()
呼叫周围放置一个块,以防万一ValueError
(a
例如,如果他们键入)。
Note if you use Python 2.x, you'll want to use raw_input()
instead of input()
. The latter will attempt to interpret the input as Python code - that can potentially be very bad.
请注意,如果你使用Python 2.x中,您需要使用raw_input()
代替input()
。后者将尝试将输入解释为 Python 代码——这可能非常糟糕。
回答by Ashwini Chaudhary
Use an if-condition:
使用 if 条件:
if 1 <= int(shift) <= 26:
#code
else:
#wrong input
Or a while loop with the if-condition:
或带有 if 条件的 while 循环:
shift = input("Please enter your shift (1 - 26) : ")
while True:
if 1 <= int(shift) <= 26:
#code
#break or return at the end
shift = input("Try Again, Please enter your shift (1 - 26) : ")
回答by Joran Beasley
while True:
result = raw_input("Enter 1-26:")
if result.isdigit() and 1 <= int(result) <= 26:
break;
print "Error Invalid Input"
#result is now between 1 and 26 (inclusive)
回答by ?smail Taha AYKA?
Another implementation:
另一个实现:
shift = 0
while not int(shift) in range(1,27):
shift = input("Please enter your shift (1 - 26) : ")#choose a shift
回答by jgranger
Try something like this
尝试这样的事情
acceptable_values = list(range(1, 27))
if shift in acceptable_values:
#continue with program
else:
#return error and repeat input
Could put in while loop but you should limit user inputs so it doesn't become infinite
可以放入 while 循环,但您应该限制用户输入,以免它变得无限