0

I want to make a function, in which I can address one of global variables using function parameter.

For example I want this code to print 6 and 10:

foo = 1
foofoo = 7
def bar(x, y):
   x += y
bar(foo, 5)
print(foo)
bar(foofoo, 3)
print(foofoo)

I looking for that to shorthen my code, 'cause I don't want to make 5 different functions to make 5 variables go through the same code segment depending on which I need in that moment. Is there any simple way to solve that problem?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • yes. Use return values... ints are immutables, so by doing `x += y` you are just changing the value of **the local variable** `x`, not the value of `foo`... – Tomerikoo Aug 19 '20 at 22:37
  • Does this answer your question? [Passing values in Python](https://stackoverflow.com/questions/534375/passing-values-in-python) – Tomerikoo Aug 19 '20 at 22:39
  • Does this answer your question? [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – wjandrea Aug 19 '20 at 22:42
  • 2
    BTW, welcome to SO! Check out the [tour], and see [ask] if you want advice. – wjandrea Aug 19 '20 at 22:49

1 Answers1

0

I think you can solve this by adding return to your functions and changing the variables by calling the function like this:

foo = 1
foofoo = 7
def bar(x, y):
   x+=y
   return x
foo=bar(foo, 5)
print(foo)
foofoo=bar(foofoo, 3)
print(foofoo)
Rick Soto
  • 26
  • 1