在下面的代码中,您将看到它要求“shift”值。我的问题是我想把输入限制在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
我怎样才能轻松地做到这一点?
使用一个
while
循环不断请求他们输入,直到您收到您认为有效的内容:您还需要在
int()
调用周围有一个try-except
块,以防收到ValueError
(例如,如果它们键入a
)。注意,如果使用Python 2.x,则需要使用
raw_input()
,而不是input()
。后者将尝试将输入解释为Python代码——这可能非常糟糕。另一个实现:
相关问题 更多 >
编程相关推荐