Python:判断真假

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25484269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:17:16  来源:igfitidea点击:

Python : While True or False

pythonwhile-loopbooleanboolean-logic

提问by Tolga Varol

I am not an experienced programmer, I have a problem with my code, I think it's a logical mistake of mine but I couldn't find an answer at http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/whilestatements.html. What I want is to check if the serial device is locked, and the different between conditions that "it is locked" and "it isn't locked" is that there are 4 commas ,,,,in the line which contains GPGGAletters. So I want my code to start if there isn't ,,,,but I guess my loop is wrong. Any suggestions will be appreciated. Thanks in advance.

我不是一个有经验的程序员,我的代码有问题,我认为这是我的逻辑错误,但我在http://anh.cs.luc.edu/python/hands-on/找不到答案3.1/handsonHtml/whilestatements.html。我想要的是检查串行设备是否被锁定,“它被锁定”和“它没有被锁定”的条件之间的区别是,,,,在包含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"

. . .

. . .

采纳答案by Martijn Pieters

Use breakto exit a loop:

使用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

The Trueand Falseline didn't do anything in your code; they are just referencing the built-in boolean values without assigning them anywhere.

TrueFalse线没有做你的代码什么; 他们只是引用内置的布尔值,而没有在任何地方分配它们。

回答by Morten Jensen

You can use a variable as condition for your whileloop instead of just while True. That way you can change the condition.

您可以将变量用作while循环的条件,而不仅仅是while True. 这样你就可以改变条件。

So instead of having this code:

因此,不要使用此代码:

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

... try this:

... 尝试这个:

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"

EDIT:

编辑:

Or as another answerer suggests, you can just breakout of the loop :)

或者正如另一位回答者所建议的那样,您可以break跳出循环:)