Luke Ogburn
Luke Ogburn

Reputation: 43

Python while loop won't stop even when condition not met

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!

Upvotes: 0

Views: 1831

Answers (2)

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

Upvotes: 1

Carcigenicate
Carcigenicate

Reputation: 45742

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
    . . . 

Upvotes: 4

Related Questions