Reputation: 23
I need to write a code that counts down from n to 1 If input is 7, output would be [7, 6, 5, 4, 3, 2, 1]
def countdown(n):
L = list(range(n,1))
while n > 0:
print(n)
n = n - 1
return L
This is what I've tried and its not working. Not even close
Upvotes: 0
Views: 569
Reputation: 2645
Your return statement is inside the while
loop, which makes it return before the whole loop is finished, furthermore, the range()
call does not indicate the negative stride.
In any case, the for
loop would be more appropriate for this case:
def countdown(n):
result = []
for x in range(n, 0, -1):
result.append(x)
return result
An even better approach would be a list comprehension:
def countdown(n):
return [x for x in range(n, 0, -1)]
Finally, the most direct solution is to simply convert the range into a list, skipping any sort of loop in your implementation:
def countdown(n):
return list(range(n, 0, -1))
Note how the variable names are in lower case by convention, to distinguish them from class names and constants (which are respectively TitleCase and CAPS).
Upvotes: 1