尝试创建一段代码,其作用类似于打开或关闭的开关


def Switch(toggle = 0):
if toggle == 0:
toggle = 1
while toggle == 1:
print('hello world')
else:
toggle = 0
time.sleep(0.3)

这是我拥有的代码,但我的问题是当我按下指定的热键时,即使我再次按下它也不会停止打印

因为您输入时从未设置toggle = 0

while toggle == 1:
print('hello world')

可能你需要

while toggle == 1:
toggle = 0
print('hello world')

您在 if 之后设置 toggle =1 并在其上使用 while 循环。 显然,它将无限次打印。 您必须定义要切换开关的次数。 这是代码:-

import time
def Switch(a):
toggle=0
for i in range(0,a):
if toggle == 0:
toggle = 1
while toggle == 1:
toggle=0
print('hello world')
if toggle == 0:
print("off")
time.sleep(1)
Switch(5)

在这里,我以 5 秒的延迟切换了 1 次。 我刚刚编辑了你的代码。 希望这对您有所帮助。

最新更新