cezaryskrodzki
cezaryskrodzki

Reputation: 11

How do I transfer variables between functions?

I have been attempting to program a calculator using the tkinter module in Python, and I have made 14 functions corresponding to each number and symbol on the calculator. The code below is for the number 1, for example.

The program doesn't return the values as it should, however. I use the values from the previous function in further functions as parameters, but they don't seem to go through and I constantly get result 0.

The variables a and b correspond to two numbers to be used in the calculation and num is a counter for the program to know when to give the number to a and when to give it to b. I have tried inserting a print in this code and a and b was printing correctly but it seems to be a problem with the return.

Any help would be appreciated.

def num1(num,a,b):
    if num == 0:
        a=a+1
        num=num+1
    elif num == 1:
        b=b+1
    return num
    return a
    return b

Upvotes: 1

Views: 83

Answers (3)

Rishabh Soni
Rishabh Soni

Reputation: 159

You can return a list, dictionary,tuple, variable. But a function can't return multiple times. You can try inserting the values in a list and then return the list.

Upvotes: 0

Gabrio
Gabrio

Reputation: 408

you need to keep in mind that the first return statement that reaches the work flow causes the end of the current function and returns the value supplied. the return a; return b lines will never be reached, the execution flow returns to the caller after the first return statement

Upvotes: 1

Den1al
Den1al

Reputation: 647

Python function only return one value. When you write return a;return b, you only return the first occurrence.

What you need to do , is pack those elements and return them as a tuple:

def num1(num,a,b):
    if num == 0:
        a=a+1
        num=num+1
    elif num == 1:
        b=b+1
    return num, a, b

Upvotes: 2

Related Questions