0

For better understanding here is a example code.

num = 0


def func(num):
    num += 1

func(num)
print(num)

This code prints 0 but I want 1(incremented by func()), how can I do that?

How can I do that? Is it possible?

Eric Whale
  • 97
  • 1
  • 9
  • 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) – Carcigenicate Nov 01 '20 at 16:54
  • I deliberately posted this question, because I couldn't find it somehow when I needed it. So I posted this with different title and link. Hope this helps – Eric Whale Nov 01 '20 at 16:57

2 Answers2

0

Long story short, you can't just put number in function and expect it to be passed by reference.

In python...

  • (act like) pass by value : whole numbers, strings or tuples
  • (act like) pass by reference : python list

You should visit here for more info about "Pass(call) by Object Reference".

https://www.geeksforgeeks.org/is-python-call-by-reference-or-call-by-value/

Eric Whale
  • 97
  • 1
  • 9
  • I know there is similar question and answer in here(stack overflow), but I couldn't find when I needed it. So I post similar question and answer with different title and link for more info. Hope this helps. – Eric Whale Nov 01 '20 at 16:54
0

In python, when you declare a variable inside a function, python treats it as a new variable. That means, any changes to that variable doesnt show up Globally.

To go through his, add global to the top. Example:

num = 0

def func():
    global num
    num += 1

func()
print(num)

Output:

1
AwesomeSam
  • 153
  • 1
  • 16