Question

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)

I need to use try-except to validate input data but obviously I do something wrong. I need to stop loop and print error if input was >=9. Could you help me guys? I really do not know what to write else

Was it helpful?

Solution

You will find this sort of problem a lot easier using a dictionary:

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

Your existing code won't raise an exception since you only try a lot of ifs and dont hit an exception condition.

You could do the same with a try by changing the last lines two:

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

However it doesn't really enhance the code .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top