-1

I am trying to access a variable that I made inside of a function on the outside. This is what I did:

    def add(a,b):
        v = a + b
        print(v)

    add(5,5)

    print(v)

However, it tells me that it is not defined when I try to print it outside of the function. I then proceeded to create the variable outside of the function first, and then change it inside of the function. This is what I did for that:

    v = 0
    def add(a,b):
        v = a + b
        print(v)

    add(5,5)

    print(v)

In this case, it just printed out 0 instead of 10 on the last line. Is there any way to keep the changes to variable while it was inside of the function instead of it staying the same?

aditpatel
  • 63
  • 6
  • 1
    Yes, you must use a `global` statement in your function. However, **this is not the recommended way to design your program**. Mutable global state is bad. Avoid it at all costs. – juanpa.arrivillaga Apr 30 '20 at 23:57

1 Answers1

-1

I think you need to add a global keyword in front of the variable in the function.

edit

I didn’t see the comment on the original post but to repeat his point - it’s typically a bad practice to use globals.

RohanP
  • 352
  • 1
  • 5