1

I have a global variable foo. I am using a function to add a number (which is sent as parameter to the function) to foo. The first time I call this function, it runs fine, but the second time I run this, it only gives me the sum of initial value of foo and the number passed as parameter. I am new to python and following is my code.

foo = 5
def add_number_to_foo(num):
    global foo
    return foo + num

add_number_to_foo(5)  # returns 10 which is fine

add_number_to_foo(6)  # returns 11, I should have got 16

I am a newbie in python, please excuse me if the question is ignorant. Thanks.

code_noob
  • 23
  • 6

2 Answers2

2

The problem with your code is that whatever you are returning is not set back to the variable foo. Following code should fix your problem:

foo = 5
def add_number_to_foo(num):
    global foo
    return foo + num

foo = add_number_to_foo(5)  # returns 10 which is fine
print(foo)  # prints 10
foo = add_number_to_foo(6)  # returns 11, I should have got 16
print(foo)  # prints 16
learner
  • 3,168
  • 3
  • 18
  • 35
1

I did the following that worked. Based on @learner's comment.

foo = 5
def add_number_to_foo(num):
    global foo
    foo = foo + num
    return foo

add_number_to_foo(5)  # returns 10
add_number_to_foo(6)  # returns 16

Since now I have assigned the variable to foo it works perfectly fine.

code_noob
  • 23
  • 6