Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

range countdown to zero

Tags:

python

range

zero

I am taking a beginner Python class and the instructor has asked us to countdown to zero without using recursion. I am trying to use a for loop and range to do so, but he says we must include the zero.

I searched on the internet and on this website extensively but cannot find the answer to my question. Is there a way I can get range to count down and include the zero at the end when it prints?

Edit:

def countDown2(start):
#Add your code here!
    for i in range(start, 0, -1):
        print(i)
like image 284
Pashta Avatar asked Mar 28 '18 15:03

Pashta


People also ask

Does range always start at 0?

When called with one parameter, the sequence provided by range always starts with 0. If you ask for range(4) , then you will get 4 values starting with 0. In other words, 0, 1, 2, and finally 3.

Is range 0 indexed?

Generally, the index range of a list is 0 to n-1 , with n being the total number of values in the list.

Can range function count down?

As discussed, the increment between two successive numbers is determined using the step parameter in the range() function. We can count down in a for loop in Python using this. For this, the start value should be greater than the end value. The step parameter needs to have a negative value.

Does range include end?

The range() method does not include the end number because it generates numbers up to the end number but never includes the end number in its result.


2 Answers

The range() function in Python has 3 parameters: range([start], stop[, step]). If you want to count down instead of up, you can set the step to a negative number:

for i in range(5, -1, -1):
    print(i)

Output:

5
4
3
2
1
0
like image 61
user3483203 Avatar answered Oct 28 '22 13:10

user3483203


As another option to @chrisz's answer, Python has a built-in reversed() function which produces an iterator in the reversed order.

start_inclusive = 4
for i in reversed(range(start_inclusive + 1)):
   print(i)

outputs

4
3
2
1
0

This can be sometimes easier to read, and for a well-written iterator (e.g. built-in range function), the performance should be the same.

like image 36
Wehrdo Avatar answered Oct 28 '22 13:10

Wehrdo