为什么这个功能不能正常工作?

Why does this function not work properly?

我不明白为什么 auto_clock() 功能可以正常工作,但 clock_time_add() 功能。第一个函数会打印出 1、2、3 中的一列列表,...这是预期的,而第二个函数只会打印出一列零。

这是第一个函数的输出:

这是第二个的输出:

这是代码:

import time

def auto_clock():
    second, minute, hour, day = -1, 0, 0, 1
    while True:
        second += 1
        time.sleep(1) 
        if second == 60:
            second = 0
            minute += 1        
        if minute == 60:
            minute = 0
            hour += 1
        if hour == 24:
            hour = 0
            day += 1
        time_clock = [day, hour, minute, second]
        return time_clock

def clock_time_add():
    while True: 
        time_clock = auto_clock()
        print(time_clock)
clock_time_add()

请考虑第一个函数中的 while 循环没有任何意义,因为 return time_clock 意味着它将在第一次迭代时退出。缩进在 Python.

中很重要

time_clock_add 中,您通过单次迭代一遍又一遍地调用 auto_clock,起始点相同,因此每次都会打印相同的内容。

在第二个函数中,您没有在一秒钟后传递更新的值。这就是为什么使用相同的 secondminutehourday 值调用第一个函数的原因。

我已更新代码以将更新后的值传递给第一个函数。

import time


def auto_clock(second, minute, hour, day):
    second += 1
    if second == 60:
        second = 0
        minute += 1
    if minute == 60:
        minute = 0
        hour += 1
    if hour == 24:
        hour = 0
        day += 1
    return second, minute, hour, day


def clock_time_add():
    second, minute, hour, day = 0, 0, 0, 1
    while True:
        second, minute, hour, day = auto_clock(second, minute, hour, day)
        print([day, hour, minute, second])
        time.sleep(1)


clock_time_add()

前 100 条记录的输出:

[1, 0, 0, 1]
[1, 0, 0, 2]
[1, 0, 0, 3]
[1, 0, 0, 4]
[1, 0, 0, 5]
[1, 0, 0, 6]
[1, 0, 0, 7]
[1, 0, 0, 8]
[1, 0, 0, 9]
[1, 0, 0, 10]
[1, 0, 0, 11]
[1, 0, 0, 12]
[1, 0, 0, 13]
[1, 0, 0, 14]
[1, 0, 0, 15]
[1, 0, 0, 16]
[1, 0, 0, 17]
[1, 0, 0, 18]
[1, 0, 0, 19]
[1, 0, 0, 20]
[1, 0, 0, 21]
[1, 0, 0,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