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

时间:2019-12-25 03:01:42

标签: python loops scope

在以下代码的底部,我设置了一个while循环,当unreadfalse时停止,该循环发生在按下按钮后的def内部(这是在RPi上)。一切都成功执行。我有更详细的评论,因为这样更容易解释。我是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()

感谢所有帮助!

2 个答案:

答案 0 :(得分:4)

一旦循环结束并且条件为假,循环将永远结束。

这里的问题是,处理程序中的unread是局部变量;它不是指全局变量,因此永远不会设置全局变量。

在更改unread之前,您必须说它是全局的:

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

答案 1 :(得分:1)

您需要在unread函数中声明handleBtnPress()全局。否则,将在函数的作用域内创建一个新的unread变量,并且外部变量将不会更改。

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