将用户输入限制在 Python 中的某个范围内

Kra*_*ubb 4 python range

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

我该如何轻松做到这一点?

scr*_*ter 7

另一个实现:

shift = 0
while not int(shift) in range(1,27):
    shift = input("Please enter your shift (1 - 26) : ")#choose a shift
Run Code Online (Sandbox Code Playgroud)


the*_*ner 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 :("
Run Code Online (Sandbox Code Playgroud)

您还需要try-exceptint()呼叫周围放置一个块,以防万一ValueErrora例如,如果他们键入)。

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