-2

I wish to ask that I want to take data and data2 from number() and transfer it to take() in which I can use it to print at the main method

def number():
    global data
    data=1
    global data2
    data2=2
    
def take():
    global finalAns
    finalAns=data+data2
    
print(finalAns)

After writing the code, the error I obtained is

NameError: name 'finalAns' is not defined

Why is this so? I thought that all variable that has a global attribute can be passed to other methods.

RyanLIM
  • 17
  • 1
  • 12
  • 2
    you first need to execute the number() and take() functions – SidoShiro92 May 24 '22 at 14:51
  • 2
    Using global variables isn't a good habit, consider using return in your function instead, in your example you need to call `number()` then `take()`, else `finalAns` isn't defined – Marius ROBERT May 24 '22 at 14:52

1 Answers1

3

Don't use globals. (There are ways you can do this, but don't.)

def number():
    data = 1
    data2 = 2
    return data1, data2
    
def take(data1, data2):
    finalAns = data + data2
    return finalAns
    
print(take(*number())  # 3

Or:

data1, data2 = number()
finalAns = take(data1, data2)
print(finalAns)

Any information that you want to get from a function should be returned by it. Any information that you want to give to a function should be a parameter. The caller isn't required to use the same names for the arguments or the return values that are used inside the function:

x, y = number()  # x, y = 1, 2
z = take(x, y)   # z = 3
print(finalAns)
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Albeit correct, the use of * might be confusing if the OP is new to python. Maybe it would be more clear to also include a more traditional approach, storing the result of number in two variables and call take passing two parameters. –  May 24 '22 at 14:53