Limiting user input to a range in Python

倖福魔咒の 提交于 2019-11-29 07:55:01

Use a while loop to keep asking them for input until you receive something you consider valid:

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

You'll also want to have a try-except block around the int() call, in case you get a ValueError (if they type a for example).

Note if you use Python 2.x, you'll want to use raw_input() instead of input(). The latter will attempt to interpret the input as Python code - that can potentially be very bad.

Another implementation:

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)

Try something like this

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

Could put in while loop but you should limit user inputs so it doesn't become infinite

Use an if-condition:

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

Or a while loop with the if-condition:

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) : ")  
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!