简体   繁体   English

如何修复我的递归倒计时 python 函数的代码,以便它只打印“LIFT OFF!” 一次?

[英]How do I fix my code for my recursive countdown python function so that it only prints “LIFT OFF!’ once?

#!/usr/bin/env python

import time

def countdown(num):
  if num <= 0:
    return num
  else:
    time.sleep(0.1)
    print(num)
    countdown(num - 1)
    print(“LIFT OFF!”)

This should work:这应该有效:

#!/usr/bin/env python

import time

def countdown(num):
  if num <= 0:
    print('LIFT OFF!')
    return num
  else:
    time.sleep(0.1)
    print(num)
    countdown(num - 1)

here's the output:这是输出:

>>> countdown(4)
4
3
2
1
LIFT OFF!
>>> 

If you only want lift off to print once, then print it once:如果你只是想lift off打印一次,然后打印一次:

import time

def countdown(num):
  if num <= 0:
    return num
  else:
    time.sleep(0.1)
    print(num)
    countdown(num - 1)

countdown(5)
print('LIFT OFF!')

Output:输出:

5
4
3
2
1
LIFT OFF!

Now the countdown() function does just one thing, which is print numbers after a delay.现在countdown()函数只做一件事,即在延迟后打印数字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的代码为每一行打印“未找到”,如果搜索不成功,我如何让它只打印一次“未找到”? - My code prints “Not Found” for every line, how do i get it to only print “Not Found” once if the search is unsuccessful? 初学者 Python:如何修复此 function 检查我的代码,以便它循环返回以允许玩家选择 - Beginners Python: How do I fix this function check in my code so that it loops back to allowing the player to pick a choice 如何修复将列表转换为字符串的递归函数 - How do I fix my recursive function that converts a list to a string 如何修复我的代码以使其自动化? - How do I fix my code so that it is automated? 如何修复我的Python函数,使其返回输入提示? - How do I fix my Python function so that it returns with input prompts? 我如何在 Python 中修复我的(据说是 while 循环或 if 语句)骰子模拟器,以便它在登陆 6 之前打印其尝试次数? - How do I fix my (supposedly while-loop or if-statement) dice-simulator in Python so it prints the amount of tries its taken before landing on a 6? 我该如何制作它,以便每个循环每次出现只打印一次? - How do I make it so it only prints once per occurrence per loop? 如何修复我的代码,以便它反转我列表中的元素? - How do I fix my code, so it reverses the elements in my list? 一旦到达 python 代码中的最后一个字母,如何打破这个递归循环? - How to break this recursive loop once I reach the last letter in my python code? 如何做到这一点,因此我只需要引用一次我的api密钥? - How do I make it so I only need my api key referenced once?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM