Making a variable formed in one def x (): used in other def y ():

def menu():
    print("The calculator can do the following:")
    print("1) Sum")
    print("2) Differentiation")
    print("3) Multiplication")
    print("4) Division")
    print("5) Times itself")
    print("The chosen numbers are", " ", int(number1), " ", "and", " ", int(number2), sep="")
    global choice
    choice = input("Please choose a choice (1-5): ")
    
def main_programme():
    action == int(choice)
    if (action == 1):
        print("sum", " ", int(number1), " ", "+", " ", int(number2), " ", "=", " ", int(number1) + int(number2), sep="")
    elif (action == 2):
        print("Differentiation", " ", int(number1), " ", "-", " ", "int(number2)", " ", "=", " ", int(number1) + int(number2), sep="")
    elif (action == 3):
        print("Multiplication", " ", int(number1), " ", "*", " ", "int(number2)", " ", "=", " ", int(number1) * int(number2), sep="")  
    elif (action == 4):
        print("Division", " ", int(number1), " ", "/", " ", "int(number2)", " ", "=", " ", int(number1) / int(number2), sep="")
    elif (action == 5):
        print("Times_itself", " ", int(number1), " ", "**", " ", "int(number2)", " ", "=", " ", int(number1) ** int(number2), sep="")
    else:
        print("The choice was not recognised.")
            
number1 = input("Please give the first number: ")
number2 = input("Please give the second number: ")
menu ()
main_programme ()           
print("Thank you for using the software.")

I found out that

choice = input("Please choose from 1-5: ")
Return choice

This is local scope for the variable choice. → " the variable choice is not defined"

I understood that adding writing “global choice” would have made it usable in “def main_programme”
but that did not work either.

I have read about scope of variables, and indecents have apparently an effect on whether variables are considered local or global.

I know I can use the version below. However, apparently it is not recommended.

choice = 0

def menu():
       choice = input("Please do a choice (1-5): ")
       return choice

Thank you in advance.

The usual way to do this would be something like this (assuming return choice in the menu function and adding a choice argument to main_programme):

number1 = input("Please give the first number: ")
number2 = input("Please give the second number: ")
choice = menu()
main_programme(choice)
print("Thank you for using the software.")

Then there is no need for any global variable at all.

1 Like