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.
global cat the top of your function, and it will use the version defined at the top-level of your file, instead of creating a new variable inside the function.global cuse this in thecfglobal cis a valid solution, it's a pretty poor one. Usereturn.is Truein your if statements. For tests that return a boolean anyway (like any() and all()), it is pure noise. For the cases where it does make a difference,if blah:is almost certainly what you mean overif blah is True:.