簡體   English   中英

將用戶輸入限制為Python中的范圍

[英]Limiting user input to a range in Python

在下面的代碼中,您將看到它要求“移位”值。 我的問題是我想將輸入限制為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循環繼續詢問輸入,直到您收到您認為有效的內容:

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代碼 - 這可能非常糟糕。

另一個實現:

shift = 0
while not int(shift) in range(1,27):
    shift = input("Please enter your shift (1 - 26) : ")#choose a shift
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)

嘗試這樣的事情

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

可以放入while循環但是你應該限制用戶輸入,這樣它就不會變成無限

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM