Python:循环 True 或 False

3 投票
2 回答
58611 浏览
提问于 2025-04-18 18:26

我不是一个有经验的程序员,我在代码上遇到了问题。我觉得这是我逻辑上的错误,但在这个链接上找不到答案。
我想检查一个串行设备是否被锁定,"被锁定"和"没有被锁定"的区别在于,包含GPGGA字母的那一行有4个逗号,,,,。所以我希望我的代码在没有,,,,的情况下开始运行,但我觉得我的循环可能有问题。任何建议都非常感谢。提前谢谢大家。

import serial
import time
import subprocess


file = open("/home/pi/allofthedatacollected.csv", "w") #"w" will be "a" later
file.write('\n')
while True:
    ser = serial.Serial("/dev/ttyUSB0", 4800, timeout =1)
    checking = ser.readline();
    if checking.find(",,,,"):
        print "not locked yet"
        True
    else:
        False    
        print "locked and loaded"

. . .

2 个回答

3

你可以用一个变量来作为你 while 循环的条件,而不是单纯用 while True。这样你就可以随时改变这个条件。

所以,别再写下面这段代码了:

while True:
    ...
    if ...:
        True
    else:
        False    

...试试这样:

keepGoing = True
while keepGoing:
    ser = serial.Serial("/dev/ttyUSB0", 4800, timeout =1)
    checking = ser.readline();
    if checking.find(",,,,"):
        print "not locked yet"
        keepGoing = True
    else:
        keepGoing = False    
        print "locked and loaded"

补充:

或者像其他回答者建议的那样,你也可以直接用 break 来跳出循环 :)

7

使用 break 可以退出一个循环:

while True:
    ser = serial.Serial("/dev/ttyUSB0", 4800, timeout =1)
    checking = ser.readline();
    if checking.find(",,,,"):
        print "not locked yet"
    else:
        print "locked and loaded"
        break

你代码中的 TrueFalse 这一行其实没什么用;它们只是提到了Python里内置的布尔值,但并没有把它们赋值给任何东西。

撰写回答