4

在下面的代码中,您会看到它要求一个“移位”值。我的问题是我想将输入限制为 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

我如何轻松做到这一点?

4

5 回答 5

7

另一个实现:

shift = 0
while not int(shift) in range(1,27):
    shift = input("Please enter your shift (1 - 26) : ")#choose a shift
于 2013-11-06T19:47:44.073 回答
5

使用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 :("

您还需要try-except在呼叫周围设置一个块int(),以防您收到一个ValueError(例如,如果他们键入a)。

请注意,如果您使用 Python 2.x,则需要raw_input()使用input(). 后者将尝试将输入解释为 Python 代码——这可能非常糟糕。

于 2013-11-06T19:45:43.580 回答
3

尝试这样的事情

acceptable_values = list(range(1, 27))
if shift in acceptable_values:
    #continue with program
else:
    #return error and repeat input

可以放入while循环,但你应该限制用户输入,这样它就不会变成无限的

于 2013-11-06T19:47:51.897 回答
2
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)
于 2013-11-06T19:46:34.253 回答
1

使用 if 条件:

if 1 <= int(shift) <= 26:
   #code
else:
   #wrong input

或带有 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) : ")  
于 2013-11-06T19:43:56.050 回答