简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM