简体   繁体   中英

How do I create a function that returns a list of integers from n to 1?

How do I write a function called countdown that counts down starting from n and goes until 1 ? The function should return a list , the contents of which should be integers going from n down to 1.

def countdown(n):
    if n >= 1:
        countdown(n-1)
    print(n)

Since you want to return a list , you need to create that list in the function.

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

range creates your sequence from n to 0 (non-inclusive, which means it'll stop at 1), with a step of -1 each time.

list then converts the sequence into the list that you want returned.

This also means that you don't actually have to create a specific function for a countdown list. You can just directly call list(range(n, 0, -1)) .

Using recursion:

def countdown(n):
    if n < 1:
        return []
    return [n] + countdown(n-1)

This approach provides the "base case" and creation of a list of integers once the base is reached.

Check out this link to visualize the execution. Do let me know if you have any questions.

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