首页 > 解决方案 > 我想获得有关 Python 中的延迟和循环的帮助

问题描述

当我在函数内部有延迟的循环之前放置一个延迟时,该函数在调用时似乎没有延迟和循环。

from time import *
from random import * 

def _print(s):
    global e_times
    print(s)
    return 10

def doloop(l_delay, s_delay):
    sleep(s_delay)
    while True:
        sleep(l_delay)

doloop(_print('Hello, world!'), 20)

我期望输出必须延迟 20 秒,然后每 10 秒它必须打印“你好,世界!” 串一次。但是在执行时,它不会延迟和循环。我应该怎么办?

标签: python

解决方案


在阅读了您对要构建的程序的期望之后,我对您的功能真的没有意义......我只需使用以下代码:

from time import sleep

def _print(n, s): # n = sleep for seconds, s = string to print
    while True: # infinite loop
        print(s) # print the string
        sleep(n) # sleep for number of seconds you specify

sleep(20) # initial sleep of 20 seconds
_print("Hello, World!", 10) # run the custom print function which sleeps for n seconds and prints s string 

希望你得到你想要的。


推荐阅读