【问题标题】:Python 3: Nested while loops based timePython 3:基于时间的嵌套 while 循环
【发布时间】:2018-05-06 12:24:03
【问题描述】:

我正在尝试根据输入条件运行两个 while 循环。在此示例中,将其取出并替换为1 == 0,以便可以来回更改0 以进行测试。选择后,每个while 循环应运行10 秒,然后再次检查输入条件(替换为1 == 0)。

问题似乎在于时间比较,因为它永远不会正确评估。我错过了什么?

#!/usr/bin/env python3
import time 
import os
import bellmod
while True:
    starttime = time.time()
    print("Start time   " + str(starttime)) #Time check
    elapsedtime = 0 #Reset elasped time to 0 for each loop iteration.
    if 1 == 0: #Change this to run either loop. See if remote or local has precidence. 
        while(elapsedtime < 10):
            print("Inside remote while  " + time.strftime("%H:%M:%S")) #Time check
        elapsedtime = time.time() - starttime #Calculate elasped time.
    else:
        elapsedtime = 0
        while(elapsedtime < 10):
            print("inside bottom of local while  " + str(int(time.time() - starttime))) #Time check
        elapsedtime = time.time() - starttime #Calculate elasped time.

【问题讨论】:

  • time.sleep(10)等十秒不是更简单吗?
  • @hoefling:那你什么也做不了。
  • 仔细查看缩进。你觉得elapsedtime什么时候更新?
  • @MartijnPieters:哦,我明白了——睡觉意味着睡觉时没有指纹......
  • 当你得到解决方案时,请记得给有用的东西投票并接受你最喜欢的答案(即使你必须自己写),这样 Stack Overflow 才能正确存档问题。跨度>

标签: python time while-loop nested


【解决方案1】:

您的内部while 循环是无穷无尽的,因为elapsedtime 从未更新:

while(elapsedtime < 10):
    print("inside bottom of local while  " + str(int(time.time() - starttime))) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.

elapsedtimewhile 循环结束后更新,但从未达到。

您需要修复缩进,以便计算 elapsedtime每次循环迭代

while(elapsedtime < 10):
    print("inside bottom of local while  " + str(int(time.time() - starttime))) #Time check
    elapsedtime = time.time() - starttime #Calculate elasped time.

请注意,while 不是函数。使用 (...) 对测试表达式进行分组,但不需要或通常不使用。如果您将值作为单独的参数传递给print(),则它会为您包括一个分隔符并转换为字符串:

while elapsedtime < 10:
    print("inside bottom of local while", int(time.time() - starttime))
    elapsedtime = time.time() - starttime

如果不需要在循环中使用elapsedtime,只需内联计算即可:

while time.time() - starttime < 10:
    print("inside bottom of local while", int(time.time() - starttime))

【讨论】:

    【解决方案2】:

    您不会在循环内更改elapsedtime ...它卡在0。 缩进最后一行:

    if 1 == 0: #Change this to run either loop. See if remote or local has precidence. 
        while(elapsedtime < 10):
            print("Inside remote while  " + time.strftime("%H:%M:%S")) #Time check
            elapsedtime = time.time() - starttime #Calculate elasped time.
    else:
        elapsedtime = 0
        while(elapsedtime < 10):
            print("inside bottom of local while  " + str(int(time.time() - starttime))) #Time check
            elapsedtime = time.time() - starttime #Calculate elasped time.
    

    【讨论】:

    • 是的,缩进是问题所在,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 2020-10-09
    相关资源
    最近更新 更多