将用户输入限制在 Python 中的某个范围内 [英] Limiting user input to a range in Python
问题描述
在下面的代码中,您会看到它要求一个移位"值.我的问题是我想将输入限制为 1 到 26.
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.
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
如何轻松做到这一点?
推荐答案
使用 while
循环不断询问他们的输入,直到您收到您认为有效的内容:
Use a while
loop to keep asking them for input until you receive something you consider valid:
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 :("
您还需要在 int()
调用周围有一个 try-except
块,以防您收到 ValueError
(例如,如果他们输入 a
).
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).
请注意,如果您使用 Python 2.x,您需要使用 raw_input()
而不是 input()
.后者将尝试将输入解释为 Python 代码 - 这可能非常糟糕.
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 中的某个范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!