【问题标题】:How to break out of a While True loop in Python如何打破 Python 中的 While True 循环
【发布时间】:2022-11-13 15:52:06
【问题描述】:

我正在使用 RFID 阅读器在 Python 中读取卡片,我想检测卡片被检测到的时间(以秒、分钟和小时为单位)。

一旦检测到卡,程序就会开始运行并开始计数,但问题是当卡被移除时代码不会中断,而是即使没有检测到卡也会继续计数。

代码附在下面:

import time as tm
import serial
import readCard


def getActivity():
    # tm.sleep(3)
    while True:
        card = readCard.readCard()
        cards = card

        if card != '':
            seconds = 0
            minutes = 0
            hours = 0

            while True:

                print(str(hours).zfill(2) + ":"
                + str(minutes).zfill(2) + ":" 
                + str(seconds).zfill(2))

                seconds = seconds + 1
                tm.sleep(1)
                if seconds == 60:
                    seconds = 0
                    minutes = minutes + 1
                if minutes == 60:
                    minutes = 0
                    hours = hours + 1
               
        else:
            print('No Card Detected...')

getActivity()
 

如果卡被检测到,我希望时间开始计算,一旦卡被取出,程序应该开始打印“未检测到卡......”。

【问题讨论】:

    标签: python time rfid


    【解决方案1】:

    尝试声明一个布尔变量,如:run = True,当你从条件中得到你需要的东西时,声明run = False,然后它将打破循环

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 2012-12-07
      • 1970-01-01
      相关资源
      最近更新 更多