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

2024-09-25 08:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,您将看到它要求“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

我怎样才能轻松地做到这一点?


Tags: the代码inforifshiftasciicode
3条回答

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

您还需要在int()调用周围有一个try-except块,以防收到ValueError(例如,如果它们键入a)。

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

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)

另一个实现:

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

相关问题 更多 >