mardi 22 mai 2018

Unable to get return values when in if-elif-else python

I'm trying this on a larger piece of code, however to cut it short and simple, this is what I'm trying to do:

  1. To make a TUI based Menu (Like Switch case)
  2. Access functions from it, which return value
  3. Those values being passed into another options of menu

Code:

def menu():  
    ch = int(input('Choice:'))  
    a, b = 1, 1
    # li = ['', '']

    if ch is 1:
        a = 11
        # li[0] = a
        menu()
    elif ch is 2:
        b = 22
        print(a+b)
        # print(li[0]+b)
        menu()
    else:
        print('End')

menu()

When executed:

Choice:1
Choice:2
23
Choice:3
End

Expectation:

Choice:1   # Expecting a = 11
Choice:2   # Expecting 11 + 22
33         # Result to be 33
Choice:3
End

Now, I do understand that is just modifying the local copy of variable. In what way can I get the value to carry forward?

I'm assuming the 11 is value in return from some function written and the second condition is taking the value as parameter for further computation.

I tried this code with a List, however not successful with that. You can check the comments in code.

Not, just with if - else, I went after exec() function to execute, but that just was a bizarre idea.

Any other way is also appreciable.

Aucun commentaire:

Enregistrer un commentaire