0

At the bottom of the below code, I have a while loop set to stop when unread is false, which occurs inside of a def after a button is pushed (this is on an RPi). Everything is successful in execution. I have comments detailing more, since it's easier to explain that way. I'm fairly new to python, so apologies if this is a simple error.

from customWaveshare import *
import sys
sys.path.insert(1, "../lib")
import os
from gpiozero import Button

btn = Button(5) # GPIO button
unread = True # Default for use in while loop

def handleBtnPress():
    unread = False # Condition for while loop broken, but loop doesn't stop
    os.system("python displayMessage.py") # this code runs, and then stops running,

while unread is not False:
    os.system("echo running") # this is printed continuously, indicating that the code never stops even after the below line is called successfully 
    btn.when_pressed = handleBtnPress # Button pushed, go to handleBtnPress()

Thanks for any and all help!

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 3
    Two problems: 1) You're not calling `handleBtnPress` in the loop, you're just assigning the function to a variable. 2) The function is setting a local variable, not the global variable. – Barmar Dec 25 '19 at 03:05
  • @Barmar I think for 1, it's called by whatever system this is? It looks like it sets up a handler on an external button. – Carcigenicate Dec 25 '19 at 03:06
  • 1
    You don't have to assign the button's `when_pressed` attribute in the loop. Just do it once and it will call the function when the button is pressed. – Barmar Dec 25 '19 at 03:07
  • If you're new to scoping, you might want to check out [Short description of the scoping rules?](https://stackoverflow.com/q/291978/4518341) – wjandrea Dec 25 '19 at 03:12

2 Answers2

4

A loop will always end once the loop reaches the end and the condition is falsey.

The problem here is, unread in the handler is a local variable; it isn't referring to the global, so the global is never set.

You have to say that unread is global prior to changing it:

def handleBtnPress():
    global unread
    unread = False
    . . . 
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
1

You need to declare unread global in the handleBtnPress() fuction. Otherwise, a new unread variable will be created within the function's scope, and the one outside won't be changed.

def handleBtnPress():
    global unread   # without this, the "unread" outside the function won't change
    unread = False