robbotjam
robbotjam

Reputation: 49

How to make a function inside a list change a variable outside of a list

First of, I am sure that this is a repeat question so i'm sorry, but I couldn't find anything. Also keep in mind I am very new to coding in general hence the quite dumb question so if I have something like

a = 1
def fun():
    a = a + 1
fun()

is there a way to make it so that if I run this a would be equal to 2?

Upvotes: 0

Views: 57

Answers (2)

Ron 11011011
Ron 11011011

Reputation: 21

You are dealing with global variable a.

a = 1
def fun():
    global a
    a = a + 1

Upvotes: 1

Stephen Lin
Stephen Lin

Reputation: 4912

Use global. Like this:

a = 1
def fun():
    # make a a global variable here
    global a
    a = a + 1
fun()
print a

OUTPUT:

2

Upvotes: 5

Related Questions