Search code examples
pythonlistappendcountdown

Python: How to countdown a number, and append that countdown to a list


Here's my attempt at creating a countdown in which all the numbers get appended to a list.

timeleft = 3
num1 = 24 - timeleft
mylist = []


def countdown():
    while num1 != 0:
          num1 -= 1
          mylist.append(num1)

countdown()

This is a small section of a schedule making app I'm making.


Solution

  • Instead of using global variables, I'd write a countdown function which accepts a start parameter and returns a list like this:

    def countdown(start):
        return list(range(start,0,-1))
    

    Demo:

    timeleft = 3
    num1 = 24 - timeleft
    cd = countdown(num1)
    print(cd) # [21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    

    If you want to count to zero use range(start,-1,-1).