Else statement executing when it shouldnt

alex23 wuwei23 at gmail.com
Mon Jan 21 00:56:59 EST 2013


On Jan 21, 2:40 pm, eli m <techgeek... at gmail.com> wrote:
> an else statement is running when it shouldnt be. It is
> on the last line. Whenever i am in the math or game
> function, when i type in main, it goes back to the start
> of the program, but it also says not a valid function.
> I am stumped!

Here is your code with the irrelevancy stripped away:

    function = raw_input("Type in a function:")
    #start math loop
    if function == "math":
        #math code
    if function == "random number":
        #random code
    if function == "games":
        #games code
    if function == "help":
        #help code
    else:
        print ("Not a valid function")

Say you enter 'math'. It passes the first condition, so runs the math
code.
It then fails on the next 3 conditions, the last of which has an else,
so if you type _anything_ other than 'help', you'll see "Not a valid
function".

Easy answer, use `elif` ("else if") instead of else for the subsequent
tests:

    if function == "math":
        #math code
    elif function == "random number":
        #random code
    elif function == "games":
        #games code
    elif function == "help":
        #help code
    else:
        print ("Not a valid function")

Better answer: read up on real functions, and look into dictionary
dispatch:

    def f_math():
       #math code

    def f_random_number():
       #random code

    <etc>

    function_dispatcher = {
        'math': f_math,
        'random number': f_random_number,
        <etc>
    }

   while cmd == 0:
       function_name = raw_input("Type in a function:")
       if function_name in function_dispatcher:
           function_dispatcher[function_name]()
       else:
           print("Not a valid function")

To have your functions break out of the loop, use a `global` variable
or pass a context object into each function to allow them to set
`cmd`.



More information about the Python-list mailing list