简体   繁体   English

即使条件不满足,Python while 循环也不会停止

[英]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).在下面代码的底部,我有一个 while 循环设置为在unreadfalse时停止,这发生在按下按钮后的def内部(这是在 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.我对 python 相当陌生,如果这是一个简单的错误,我很抱歉。

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!感谢您的任何帮助!

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;这里的问题是,处理程序中的unread是一个局部变量; 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:在更改之前,您必须说unread是全局的:

def handleBtnPress():
    global unread
    unread = False
    . . . 

You need to declare unread global in the handleBtnPress() fuction.您需要在handleBtnPress()函数中声明unread全局。 Otherwise, a new unread variable will be created within the function's scope, and the one outside won't be changed.否则,将在函数作用域内创建一个新的unread变量,并且不会更改外部的变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM