Python-不希望字母或数字超出范围输入

时间:2014-12-14 21:07:32

标签: python exception input

我希望程序只允许数字1-4用作输入,而不是该范围之外的任何字母或数字。这是我现在的代码,但它不起作用:

 # Get the user's choice.
 choice = int(input("what would you like to do ? "))

 # Validate the choice.
 while choice < 1 or choice > 4:
    try:
        choice = int(raw_input("Enter a valid choice: "))
    except ValueError:
        print ("Please enter a numeric value.")

 # return the user's choice.
 return choice

3 个答案:

答案 0 :(得分:1)

这是您的解决方案

while True:
    try:
        choice = int(input("what would you like to do ? "))
    except ValueError:
        print ("Invalid choice.Valid choises are between 1-4.")
        continue
    if choice<1 or 4<choice:
        print ("Invalid choice.Valid choises are between 1-4.")
        continue
    else:
        print ("some codes will work on here..")

答案 1 :(得分:0)

您可以尝试这样的事情:

 def ask():
     # Get the user's choice.
     choice = raw_input("what would you like to do ? "))
     return choice

 #you can put this in while True infinite loop if you want it to ask again and again
 choice = ask()

 # Validate the choice.
 if choice.isdigit():
    if (choice > 0) and (choice < 5):
        print choice
    else:
        print "Input must be between 1 and 4!"
 else:
    print "Input must be digit!"

使用isdigit()检查字符串是否为数字。它返回True或False。这是一些文档:

https://docs.python.org/2/library/stdtypes.html#str.isdigit

我希望这有助于满足您的需求;)

答案 2 :(得分:0)

尝试这样:

def get_choice():
    while True:
        choice = raw_input("Enter a valid choice between 1 and 4: ")
        if choice.isdigit():
            if 1<= int(choice) <=4:
                print choice
                return choice
        else:
            print ("Please enter a numeric value.")

str.isdigit():检查字符串是否为数字,如果数字返回True,则返回False