在python中使用try-except验证表单

时间:2014-03-12 03:45:48

标签: python try-except

def validate(choice):
try:
   if choice == 1 or choice == 2 or choice == 3 or choice == 4 or choice == 5 or choice == 6 or choice == 7 or choice == 8:
     if choice==1:
            extrasquare()
     elif choice==2:
            drawastar()
     elif choice==3:
            drawit()
     elif choice==4:
            circle()
     elif choice==5:
            square()
     elif choice==6:
            turtle.clear()
     elif choice==7:
            turtle.bye()
     elif choice==8:
            import sys      #exit from program
            sys.exit()      #might not work in some versions of idlex
            loop = 700076
except:
    loop=8
    print("Error")



while loop == 1:
    #print options for user
    print("----------------------------")
    print("Hello")
    print("Here's you options")
    print("1- to draw a set of squares(extra picture)")
    print("2-to draw 10 stars")
    print("3-to draw nine rectangles")
    print("4-to draw a random number of random circles")
    print("5-to draw a square motion")
    print("6-to Erase everything")
    print("7-to exit from turtle")
    print("8-to  exit from python")
    print(" ")
    choice = int(input("What would you like to do? Please enter a number:"))
    validate(choice)

我需要使用try-except来验证输入数据,但显然我做错了。如果输入是> = 9,我需要停止循环和打印错误。你能帮帮我们吗?我真的不知道该怎么写

1 个答案:

答案 0 :(得分:0)

使用字典会更容易发现这类问题:

def validate(choice):
    options = {
       1: extrasquare,
       2: drawastar,
       3: drawit,
       4: circle,
       5: square,
       6: turtle.clear,
       7: turtle.bye,
       8: exit   #  Move your exit action to a separate function for simplicity
       }

    if choice in options:
       options[choice]()
    else:
       print "Error: %i is not a recognized choice" % i

您现有的代码不会引发异常,因为您只尝试了很多ifs并且没有遇到异常情况。

您可以通过更改最后两行来尝试相同的操作:

 try:
    options[choice]()
 except KeyError:
    print "Error : %i is not a recognized choice" % choice

然而,它并没有真正增强代码。