How to create a global variable in python - python

In my program I need a counter, but it just counts to one and not higher. Here is my code:
# set a counter variable
c = 0
def counter(c):
c += 1
print(c)
if c == 10:
methodXY()
def do_something():
# here is some other code...
counter(c)
this is the important part of my code. I guess the problem is that the method counter() starts with the value 0 all the time, but how can I fix that? Is it possible that my program "remembers" my value for c? Hope you understand my problem. Btw: I am a totally beginner in programming, but I want to get better

If you want to use outer variable "c" inside your function, write it as global c.
def counter():
global c
c += 1
print(c)
if c == 10:
methodXY()

You always call the function with the value 0 (like you expected). You can return "c"
and call it again.
Look:
# set a counter variable
c = 0
def counter(c):
c += 1
print(c)
return c
def do_something(c):
c=counter(c)
return c
for i in range(10):
c=do_something(c)

Related

Problem with local variable. NameError: name 'b' is not defined in python

There is something wrong with my code. I still don't understand how local variable works. The following is an example of a simple code. And I have a NameError issue. Why? How can I fix this? I need to fix this error without Global variables! And there must be variable(a) ! What should I do for the answer of this code to come out 21?
def first(a):
a = 0
b = 3
return b
def second(a):
a = 0
j = 7
return j
def result():
return first(b) * second(j) # <-NameError: name 'b' is not defined in python
print(result())
You should define what does your b and j mean in string 10:
For python you are giving noting to function, but this function is asking for some value (a), it should be like this:
def first(a):
a = 0
b = 3
return b
def second(a):
a = 0
j = 7
return j
def result():
b = 123 # Defining what are we giving to our functions
j = 5
return first(b) * second(j) # Now it will work
print(result())
So you can use b and j value, and access return values:
b = 3
return b
j = 7
return j
Think like this, when you're returning some value, it fully replaces function with that value.
Here, b is only defined within the scope of function first()
This means that any code outside of this function cannot access that variable.
Unless the variable is marked as global b it will only be accessible within that 'block' of code
Example:
# Variable not defined in a function, therefore in global scope.
a = 10
def foo():
# Variable defined in function, only accessible within function
b = 10
# NOT RECCOMENDED
# Variable marked as global and accessible anywhere after assignment
global c
c = 10
# Additional Note (Not important or useful)
# Non local overrides local variables with a variable in an outer but not global scope
d = 10
def bar():
nonlocal d
d = 20
print(a) # 10 - No error, in global scope
print(b) # Error - b not in global scope
print(c) # 10 - No error, in global scope
# nonlocal (ignore)
print(d) # Error - d not in global scope
Short answer: local variables can only be used inside the function where they are defined.
Let's look at your code to see what is going on:
def first(a):
a = 0
b = 3. # b is defined inside of `first()`
return b
def second(a):
a = 0
j = 7
return j
def result():
return first(b) * second(j) # trying to use `b` inside result() gives an error because there is no variable with that name defined here.
print(result())
See the comments on the relevant lines. I don't know what you are trying to do here, so I can't give any suggestions about how to fix it.

Changing a local variable in a function from another function

First, here's my example code:
EDIT: I should have specified, in my real code, that_func() is already returning another value, so I want it to return one value, and change c in addition
EDIT 2: Code edited to show what I mean
def this_func():
c=1 # I want to change this c
d=that_func()
print(c, d)
def that_func():
this_func.c=2 #Into this c, from this function
return(1000) #that_func should also return a value
this_func()
What I want to do is change the local variable c in this_func() to the value I assign it in that_func(), so that it prints 2 instead of 1.
From what I've gathered online, this_func.c=2 should do just that, but it doesn't work. Am I doing something wrong, or have I misunderstood?
Thanks for any and all help.
Yes, you misunderstood.
functions are not class. You can't access variables of a function like that.
Obviously, it's not the smartest of code that can be written, but this code should give an idea about how to use variables of a function.
def this_func():
c=1 # I want to change this c
c=that_func(c) # pass c as parameter and receive return value in c later
print(c)
def that_func(b): # receiving value of c from this_func()
b=2 # manipulating the value
return b #returning back to this_func()
this_func()
Wrap it in an object and pass it to that_func:
def this_func():
vars = {'c': 1}
d = that_func(vars)
print vars['c'], d
def that_func(vars):
vars['c'] = 2
return 1000
Alternatively, you can pass it in as a regular variable and that_func can return multiple values:
def this_func():
c = 1
c, d = that_func(c)
print c, d
def that_func(c):
c = 2
return c, 1000

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.
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()
To summarise a few of these answers, you have 3 basic options:
Declare the variable as global at the top of your function
Return the local instance of the variable at the end of your function
Pass the variable as an argument to your function
You can also pass the array c into the function after declaring it. As the array is a function argument the c passed in will be modified as long as we don't use an = statement. This can be achieved like this:
def cf(n, c):
c.extend(range(5))
print c
if any((i>3) for i in c) is True:
print 'hello'
if __name__ == '__main__':
c = []
cf(1, c)
print c
For an explanation of this see this
This is preferable to introducing global variables into your code (which is generally considered bad practice). ref
Try this
c = []
def cf(n):
global c
c = range (5)
print c
if any((i>3) for i in c) is True:
print 'hello'
cf(1)
print c
If you want your function to modify c then make it explicit, i.e. your function should return the new value of c. This way you avoid unwanted side effects:
def cf(n, b):
"""Given b loops n times ...
Returns
------
c: The modified value
"""
c = [transformation of b]
...
return c # <<<<------- This
c = cf(1)

I keep on getting NameError: name 'a' is not defined?

def main():
a == 3
b = a + 1
c = b + 1
print(a)
if (a<0):
print(a<0)
print(c)
else:
print('a is not less than 0')
print(a)
I watched the khan academy video #1 on Python programming and tried to duplicate it but it kept on giving the error above.
Thanks for your help
I am a first time python user
You are not assigning to a; you are instead testing for equality with a double ==:
a == 3
Since you didn't assign anything to a yet to compare with 3, that results in a NameError.
Remove one = sign to assign instead:
a = 3
This all assumes that the rest of your code is indented correctly to match the rest of your function:
def main():
a = 3
b = a + 1
c = b + 1
print(a)
if (a<0):
print(a<0)
print(c)
else:
print('a is not less than 0')
print(a)
== is used for comparison tests. You need to use = for variable assignment:
a = 3
Also, as your code currently stands, the stuff outside of main will not be able to access a because it is local to the function. Hence, you need to indent it one level:
def main():
a = 3
b = a + 1
c = b + 1
print(a)
if (a<0):
print(a<0)
print(c)
else:
print('a is not less than 0')
print(a)
main()
I think you want the following code:
def main():
a = 3
b = a + 1
c = b + 1
print(a)
if (a<0):
print(a<0)
print(c)
else:
print('a is not less than 0')
print(a)
main()
You want the if statements to be inside the function that you're making, in this case main(). Otherwise, 'a' will not be defined because it is inside the function main(). Welcome to python, and to stack overflow!

Why doesn't program print value?

I am wondering why the following program does not print 'b'. It is is very simple code; I think it must work; and do not know the reason why it doesn't.
def a():
if b > 10:
print 'b'
sys.exit(1)
# main
while 1:
a()
b += 1
b is global variable. Actual code is more complicated but the structure is the same as mine. I guess when I call a() function and if b is greater than 10, it shows 'b'. However, it does not go inside if-statement.
Would you help me out how to solve?
Thanks.
Globals are horrid learn not to use them, try something like this
import sys
def a(value):
if value > 10:
print value
print "Greater than 10!"
sys.exit(0)
b = 0
while True:
a(b)
b += 1
Another answers suggests not using globals, and I agree. If you still want to use globals, you should define b outside of the loop first.(if you do, then please post the complete code, because apart from that, it should work (and it does)).
Now, global b in the function definition is not necessary, because python guesses it is a global variable when you try to access it before assigning. But since it is not defined it raises an NameError:
NameError: global name 'b' is not defined
If you don't see that, so there's something else, you're not showing the actual code that has a problem.
This gives you in the end, something similar:
import sys
def a():
global b
if b > 10:
print 'b'
sys.exit(1)
b = 0
# main
while 1:
a()
b += 1
Global vars are not the usual way to go. You may prefer the usage of nested functions instead:
import sys
def outer(value=0):
count = [value]
print "started at:", count[0]
def inner(x=1):
print "current val:", count[0]
count[0] += x
if count[0] > 10:
print "stopped at:", count[0]
sys.exit(0)
return inner
f = outer(5)
while True:
f(1)
You need to define b before "+="ing it.
def a():
if b > 10:
print 'b'
sys.exit(1)
# main
b = 0 # HERE
while 1:
a()
b += 1
By the way, as many had told you: avoid globals.
just my 2 cents: forget global variables.
anyway, this should work
def a():
global b
if b > 10:
print 'b'
sys.exit(1)
EDIT FUUUUUUUUUUUUUUU
Although I fully agree with Jackob on how you should use functions arguments and avoid globals, just for the record, here's the solution with global:
def a():
global b
if b > 10:
print 'b'
sys.exit(1)
# main
b = 0
while 1:
a()
b += 1

Categories

Resources