Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remember Array value after Function call

If I write this:

c = []

def cf(n):
    c = range (5)
    print c
    if any((i>3) for i in c) is True:
        print 'hello'

cf(1)

print c

Then I get:

[1, 2, 3, 4]
hello
[]

I'm really new to programming, so please explain it really simply, but how do I stop Python from forgetting what c is after the function has ended? I thought I could fix it by defining c before the function, but obviously that c is different to the one created just for the function loop.

In my example, I could obviously just write:

c = range (5)
def cf(n)

But the program I'm trying to write is more like this:

b = [blah]
c = []
def cf(n):
    c = [transformation of b]
    if (blah) is True:
       'loop' cf
    else:
cf(1)
g = [transformation of c that produces errors if c is empty or if c = b]

So I can't define c outside the function.

like image 694
Patrik333 Avatar asked Apr 07 '26 11:04

Patrik333


1 Answers

In python you can read global variables in functions, but you cant assigned to them by default. the reason is that whenever python finds c = it will create a local variable. Thus to assign to global one, you need explicitly specify that you are assigning to global variable.

So this will work, e.g.:

c = [1,2,3]

def cf(): 
    print(c) # it prints [1,2,3], it reads global c

However, this does not as you would expect:

c = [1,2,3]

def cf(): 
    c = 1 # c is local here.
    print(c) # it prints 1


cf()
print(c) # it prints [1,2,3], as its value not changed inside cf()

So to make c be same, you need:

c = [1,2,3]

def cf(): 
    global c
    c = 1  # c is global here. it overwrites [1,2,3]
    print(c) # prints 1


cf()
print(c) # prints 1. c value was changed inside cf()
like image 150
Marcin Avatar answered Apr 09 '26 00:04

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!