Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中将用户输入限制在一个范围内_Python_Range - Fatal编程技术网

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

在Python中将用户输入限制在一个范围内,python,range,Python,Range,在下面的代码中,您将看到它要求输入“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 yo

在下面的代码中,您将看到它要求输入“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
对于句子中的字符:
如果validleters中的字符或space中的字符:#检查
newString+=字符#可用字符
班次=输入(“请输入班次(1-26):”)#选择班次
结果=[]
对于CHIN新闻字符串:
x=ord(ch)#确定ASCII码中的位置
x=x+shift#应用密码的移位
结果:追加(chr(x if 97使用if条件:

if 1 <= int(shift) <= 26:
   #code
else:
   #wrong input
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) : ")  

<代码>如果1 使用<代码>而Road继续请求它们输入直到收到您认为有效的东西:

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 :("
shift=0
当1>shift或26
您还需要在
int()
调用周围使用
try except
块,以防出现
ValueError
(例如,如果他们键入
a

注意:如果使用Python 2.x,您将希望使用
raw\u input()
而不是
input()
。后者将尝试将输入解释为Python代码-这可能非常糟糕。

如果为True:
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)
结果=原始输入(“输入1-26:”)
如果result.isdigit()和1是另一个实现:

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

试试这样的

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

可以放入while循环,但您应该限制用户输入,使其不会变成无限

创建while循环,并不断请求输入,直到他们给您提供有效的内容。您的值为1,应该是
范围(1,27)