Can someone explain why the gloabl variable x & y are not recognized in printfunc,
code.py
global x
global y
def test(val_x=None,val_y=None)
x = val_x
y = val_y
printfunc()
def printfunc():
print('x',x)
print('y',y)
if __name__ = '__main__':
test(val_x=1,val_y=2)
place the global inside test().
global is used inside functions so that we can change global variables or create variables that are added to the global namespace. :
def test(val_x=None,val_y=None):
global x
global y
x = val_x
y = val_y
printfunc()
The global keyword is used inside code block to specify, that declared variables are global, not local. So move global inside your functions
def test(val_x=None,val_y=None): #you also forgot ':' here
global x, y
x = val_x
y = val_y
printfunc()
def printfunc():
global x, y
print('x',x)
print('y',y)
Related
In python I wrote:
registered_to = 0
def execute_data():
registered_to += response.text.count("<div class=\"info-msg\">")
But I'm getting:
registered_to += response.text.count("<div class=\"info-msg\">")
UnboundLocalError: local variable 'registered_to' referenced before assignment
Is this what you want?
registered_to = 0
def execute_data():
global registered_to
registered_to += response.text.count("<div class=\"info-msg\">")
global keyword must be used whenever you wish to modify/create global variables from a non-global scope like a function. If you are just using a global variable from a non-global scope and not modifying it, you need not use the keyword.
Examples
Using global variable in a non-global scope but not modifying it
wish = "Hello "
def fun():
print(wish)
fun()
Using global variable in a non-global scope and modifying it as well
wish = "Hello "
def fun():
word += "World"
print(wish)
fun()
I got a code from the internet for my project, and there is a function with parameter that i need to make change of global variable value
it is a flask request json app, i use the ifttt to send json to this project. i've tried to change by this code but it won't change, the X always in 1
X=1
#app.route('/',methods=['POST'])
def index():
req = request.get_json(silent=True, force=True)
val = processRequest(req)
#print(val)
r = make_response(json.dumps(val))
r.headers['Content-Type'] = 'application/json'
return r
def processRequest(req):
device = req['device']
state = json.loads(req['state'])
#print(state)
if (device=='bedlamp'):
global()['X']=int(30)
i want it when the ifttt send device bedlamp, the value of global variable turn to 30, can anybody help me?
To change a global variable called X inside a function you have to do:
1) bring the variable into the function scope
global X
2) change its value
X = 30
so:
def abc():
global x
x = 30
You need to use the global keyword, like this:
def processRequest(req):
device = req['device']
state = json.loads(req['state'])
if (device=='bedlamp'):
global X
X = 30
Basically I have this section of code that goes like so:
def start():
def blockA():
y = 3
x = 4
print("hello")
blockA()
def blockB():
if x !=y:
print("not the same")
blockB()
start()
However, this gives me an error saying that x and y are not defined. How would I go about referencing the x and y variables in blockB?
You need to return the variables in blockA function and call that function in your second function.
def blockA():
y = 3
x = 4
print("hello")
return x,y
def blockB():
x,y=blockA()
if x !=y:
print("not the same")
This should work for you.
I am trying to make a variable in Python go up by one continuously, but inside a function. What I am using is something like this:
def func1():
def set1():
x=5
y=10
##lots of code
x+=1
y+=1
def func2():
while True:
func1()
set1()
func2()
I'm wondering if there is a much better way to do this?
Probably the best way to do this is to put the definition of x and y into function 2, and have them be inputs and outputs of function 1.
def func1(x, y):
##lots of code
x+=1
y+=1
return x, y
def func2():
x = 5
y = 10
while True:
x, y = func1(x, y)
Other alternatives include defining x and y globally and using global x, global y or using mutable default arguments to make the function retain state, but generally better to not resort to these options if you don't have to.
A bit of code review and recommendations:
def func1():
def set1():
x=5
y=10
##lots of code
x+=1
y+=1
def func2():
while True:
func1()
set1() # This won't work because set1 is in the local scope of func1
# and hidden from the global scope
func2()
Looks like you want the function to count each time it is called. May I suggest something like this?:
x=5
y=10
def func1():
global x, y
x+=1
y+=1
print x, y
def func2():
while True:
func1()
func2()
Better than using a global variable, stick them in a mutable object in a nested scope:
Counts = dict(x=5, y=10)
def func1():
Counts['x'] += 1
Counts['y'] += 1
print Counts['x'], Counts['y']
def func2():
while True:
func1()
func2()
x = None
y = None
def set1():
global x, y
x=5
y=10
def func1():
global x, y
x+=1
y+=1
def func2():
while True:
func1()
set1()
func2()
** just saw the edit on going up instead of down - modified code to suit**
It's hard to tell from your question what your actual use case is but I think a Python generator may be the right solution for you.
def generator(x, y):
yield x,y
x += 1
y += 1
Then to use:
if __name__ == "__main__":
my_gen = generator(10,5)
for x,y in my_gen:
print x,y
if x+y > 666:
break
This may be a slightly advanced for someone new to Python. You can read up on generators here: http://anandology.com/python-practice-book/iterators.html
First of all, the set1 function doesn't seem to do much at all, so you could take it away.
If you want to keep count of the number of calls or keep state between calls, the best, more readable way is to keep this inside an object:
class State(object):
def __init__(self):
self._call_count = 0
self.x = 5
def func1(self):
self._call_count += 1
self.x = ... Whatever
def func2():
state = State()
while True:
state.func1()
I am trying to store a value in a module level variable for later retrieval.
This function when called with a GET method throws this error: local variable 'ICS_CACHE' referenced before assignment
What am I doing wrong here?
ICS_CACHE = None
def ical_feed(request):
if request.method == "POST":
response = HttpResponse(request.POST['file_contents'], content_type='text/calendar')
response['Content-Disposition'] = 'attachment; filename=%s' % request.POST['file_name']
ICS_CACHE = response
return response
elif request.method == "GET":
return ICS_CACHE
raise Http404
I constructed a basic example to see if a function can read module constants and it works just fine:
x = 5
def f():
print x
f()
---> "5"
Add
global ISC_CACHE
as the first line of your function. You are assigning to it inside the function body, so python assumes that it is a local variable. As a local variable, though, you can't return it without assigning to it first.
The global statement lets the parser know that the variable comes from outside of the function scope, so that you can return its value.
In response to your second posted example, what you have shows how the parser deals with global variables when you don't try to assign to them.
This might make it more clear:
x = 5 # global scope
def f():
print x # This must be global, since it is never assigned in this function
>>> f()
5
def g():
x = 6 # This is a local variable, since we're assigning to it here
print x
>>> g()
6
def h():
print x # Python will parse this as a local variable, since it is assigned to below
x = 7
>>> h()
UnboundLocalError: local variable 'x' referenced before assignment
def i():
global x # Now we're making this a global variable, explicitly
print x
x = 8 # This is the global x, too
>>> x # Print the global x
5
>>> i()
5
>>> x # What is the global x now?
8