【问题标题】:Please explain why programm would go into the if statement [duplicate]请解释为什么程序会进入if语句[重复]
【发布时间】:2019-08-20 21:00:36
【问题描述】:

下面是一个简单的 python 代码,它只是打印带有延迟的实际时间/日期。如果有人可以(尽可能简单地)向我解释程序何时以及为什么进入 if 语句(如果 exitFlag :),我将非常感激该语句是什么?如果 exitFLag == 真?对不起,我不明白这一行。

我尝试使用类似且更简单的代码来复制该函数。但是这里程序不会进入 if 语句。我希望有人可以帮助我更好地理解代码。

test = 0
counter = 10
while counter:
    if test:
        print("if-statement is called")
        break
    print("still in loop")
    counter -=1
import threading
import time


exitFlag = 0

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):        
        threading.Thread.__init__(self)                 
        self.threadID = threadID                        
        self.name = name
        self.counter = counter

    def run(self):                                      
        print("Starting " + self.name)
        print_time(self.name, self.counter, 5)          
        print("Exiting " + self.name)


def print_time(threadName, counter, delay):
    while counter:
        if exitFlag:                                   
            threadName.exit()
        time.sleep(delay)
        print("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1


thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

thread1.start()
thread2.start()
thread1.join()
thread2.join()

print("Exiting main thread")

【问题讨论】:

标签: python-3.x if-statement while-loop


【解决方案1】:

所以在真值测试中(当你检查某件事是真还是假时),你可以使用很多不同的值。

Python's Docs说可以用下面的值来表示假:

  • None
  • False
  • 任何数字类型的零,例如0, 0L, 0.0, 0j。
  • 任何空序列,例如,''、()、[]。
  • 任何空映射,例如 {}。
  • 用户定义类的实例,如果该类定义了 __nonzero__() 或 __len__() 方法,则该方法返回整数零或布尔值 False。

其他任何情况都为真。

在这个程序中,exitFlag 是一个整数。代码

if exitFlag:                                   
        threadName.exit()

基本上是说:“如果exitFlag 不是 0,退出线程”

话虽如此,代码似乎永远不会从0 更改exitFlag,所以这个 if 语句可能永远不会被输入

【讨论】:

    猜你喜欢
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多