Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Global - local variables
#1
Hello All

I am struggling with using local or global variables. I want to change a variable from 0 to 1 and vis versa within a function when something changes. If I set the variable as a global variable then it is always reset to 0 when the function is called. If I do not declare it globally then it will produce an error of not declared. The other option is to declare it locally before my IF statement but it would then be set to the declared state each time. Hope this makes some sense. The test code is shown below. The If statement is only to be called once, hence the Flag variable

Flag = 0
nuserySWdatabase = 0 # this would be from database but is set to 0 for testing

def nuseryControlFunction(nuserySWdatabase):
    if ( nuserySWdatabase == 0 and Flag == 0):
        print ("pump on")
        Flag = 1
        print Flag
    else:
        print ("pump off")
        Flag = 0

while 1:
    nuseryControlFunction(nuserySWdatabase)
    print Flag
Reply
#2
you need to declare it global.
Flag = 0
nuserySWdatabase = 0 # this would be from database but is set to 0 for testing
 
def nuseryControlFunction(nuserySWdatabase):
    global Flag
    if ( nuserySWdatabase == 0 and Flag == 0):
        print ("pump on")
        Flag = 1
        print Flag
    else:
        print ("pump off")
        Flag = 0
 
while 1:
    nuseryControlFunction(nuserySWdatabase)
    print Flag
Yet way way better would for your function to return the flag. If you don't change it inside the function, you can access flag from global scope.

nuserySWdatabase = 0 # this would be from database but is set to 0 for testing
flag = False
def nuseryControlFunction(nuserySWdatabase):
    if nuserySWdatabase == 0 and not flag:
        print("pump on")
        return True
    else:
        print("pump off")
        return False
 
while True:
    flag = nuseryControlFunction(nuserySWdatabase)
    print(flag)
But still better would be to if your function has flag as second parameter (if you need it at all - from your code I cannot decide if it really needed).

nuserySWdatabase = 0 # this would be from database but is set to 0 for testing
flag = False
def nuseryControlFunction(nuserySWdatabase, flag):
    if nuserySWdatabase == 0 and not flag:
        print("pump on")
        return True
    else:
        print("pump off")
        return False
 
while True:
    flag = nuseryControlFunction(nuserySWdatabase, flag)
    print(flag)
Also, note your names do not comply with PEP8 recommendations but I kept them
Motorhomer14 likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Dec-17-2020, 05:31 PM)buran Wrote: you need to declare it global.
Flag = 0
nuserySWdatabase = 0 # this would be from database but is set to 0 for testing
 
def nuseryControlFunction(nuserySWdatabase):
    global Flag
    if ( nuserySWdatabase == 0 and Flag == 0):
        print ("pump on")
        Flag = 1
        print Flag
    else:
        print ("pump off")
        Flag = 0
 
while 1:
    nuseryControlFunction(nuserySWdatabase)
    print Flag
Yet way way better would for your function to return the flag. If you don't change it inside the function, you can access flag from global scope.

nuserySWdatabase = 0 # this would be from database but is set to 0 for testing
flag = False
def nuseryControlFunction(nuserySWdatabase):
    if nuserySWdatabase == 0 and not flag:
        print("pump on")
        return True
    else:
        print("pump off")
        return False
 
while True:
    flag = nuseryControlFunction(nuserySWdatabase)
    print(flag)
But still better would be to if your function has flag as second parameter (if you need it at all - from your code I cannot decide if it really needed).

nuserySWdatabase = 0 # this would be from database but is set to 0 for testing
flag = False
def nuseryControlFunction(nuserySWdatabase, flag):
    if nuserySWdatabase == 0 and not flag:
        print("pump on")
        return True
    else:
        print("pump off")
        return False
 
while True:
    flag = nuseryControlFunction(nuserySWdatabase, flag)
    print(flag)
Also, note your names do not comply with PEP8 recommendations but I kept them

Thanks for the quick reply, I ended up going with the return script as this looks better and makes more sense.

Not sure what the PEP8 naming is, I will have to look this up. Most of my variable naming comes from where I do jQuery and php.

As for not having the Flag in the end I will be adding in time to the ON IF statement so if the pump is on for too long then the program will go into a shutdown status. So within the pump on statement a time of when it comes on will be stored, so this needs to only happen once
Reply
#4
(Dec-17-2020, 05:38 PM)Motorhomer14 Wrote: Not sure what the PEP8 naming is
https://www.python.org/dev/peps/pep-0008/
Motorhomer14 likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Slight change to your code but at least now it seems to be working

def nuseryControlFunction(nuserySWdatabase, nersFlag):
    if nuserySWdatabase == 0 and nersFlag == False:
        print ("pump on")
      #  GPIO.output(pump, GPIO.LOW)
        offTime = datetime.datetime.now() + datetime.timedelta(seconds=30)
        print offTime
        return True
    if nuserySWdatabase == 1:
        print ("pump off")
      #  GPIO.output(pump, GPIO.HIGH)
        return False
Reply
#6
don't do nersFlag == False. nersFlag is bool in itself. not nersFlag is the same as nersFlag == False.
No need (and really doesn't make sense) to compare it to False or True.

Also, it looks like you use python2 (you use print statement on line 6, in which case the brackets on lines 3 and 9 are not needed). But you should switch to python3. python2 is dead, no longer supported as of 1 Jan 2020.
By the way nuserySWdatabase looks like bool too. Is that the case? If is just 0 or 1 you can benefit from reading https://docs.python.org/3/library/stdtyp...ue-testing and again not comparing it to 0 and 1.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
(Dec-17-2020, 06:04 PM)buran Wrote: don't do nersFlag == False. nersFlag is bool in itself. not nersFlag is the same as nersFlag == False.
No need (and really doesn't make sense) to compare it to False or True.

Also, it looks like you use python2 (you use print statement on line 6, in which case the brackets on lines 3 and 9 are not needed). But you should switch to python3. python2 is dead, no longer supported as of 1 Jan 2020.
By the way nuserySWdatabase looks like bool too. Is that the case? If is just 0 or 1 you can benefit from reading https://docs.python.org/3/library/stdtyp...ue-testing and again not comparing it to 0 and 1.

Thanks changed that, working ok on this part. Now need to do same with a time variable to shut it down if over run on pump
Reply
#8
Dont suppose you would be able to let me know why a time variable when returned is giving the error
'NoneType' object is not iterable

I only get this error when pump is ON. When OFF I get return of zero.


import datetime

nersFlag = False
nuserySWdatabase = 0
nersOffTime = 0

def nuseryControlFunction(nuserySWdatabase, nersFlag, nersOffTime):
    if nuserySWdatabase == 0 and not nersFlag:
        print ("pump on")
      #  GPIO.output(pump, GPIO.LOW)
        nersOffTime = datetime.datetime.now() + datetime.timedelta(seconds=30)
        return True, nersOffTime
    if nuserySWdatabase == 1:
        print ("pump off")
      #  GPIO.output(pump, GPIO.HIGH)
        nersOffTime = 0
        return False, nersOffTime
   # if nersOffTime == now:
      #  print "shutdown"

while True:
    now = datetime.datetime.now()
    nersFlag, nersOffTime = nuseryControlFunction(nuserySWdatabase, nersFlag, nersOffTime)
    print nersOffTime
Reply
#9
Post the full traceback you get, in error tags
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#10
Ah, what do you think happens when nuserySWdatabase == 0 and nersFlag is True? That will happen when you change flag to True in first iteration. Neither of your conditions is True, so your function returns the default None.

You can visualise execution here and see for yourdelf. http://www.pythontutor.com/visualize.html#mode=edit
Motorhomer14 likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  It's saying my global variable is a local variable Radical 5 1,097 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Trying to understand global variables 357mag 5 1,064 May-12-2023, 04:16 PM
Last Post: deanhystad
  Delete all Excel named ranges (local and global scope) pfdjhfuys 2 1,689 Mar-24-2023, 01:32 PM
Last Post: pfdjhfuys
  Global variables or local accessible caslor 4 984 Jan-27-2023, 05:32 PM
Last Post: caslor
  global variables HeinKurz 3 1,100 Jan-17-2023, 06:58 PM
Last Post: HeinKurz
  How to use global value or local value sabuzaki 4 1,104 Jan-11-2023, 11:59 AM
Last Post: Gribouillis
  Clarity on global variables JonWayn 2 904 Nov-26-2022, 12:10 PM
Last Post: JonWayn
  Global variables not working hobbyist 9 4,614 Jan-16-2021, 03:17 PM
Last Post: jefsummers
  Global vs. Local Variables Davy_Jones_XIV 4 2,594 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV
  from global space to local space Skaperen 4 2,269 Sep-08-2020, 04:59 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020