Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decreasing for loops in Python impossible?

I could be wrong (just let me know and I'll delete the question) but it seems python won't respond to

for n in range(6,0):     print n 

I tried using xrange and it didn't work either. How can I implement that?

like image 585
Gal Avatar asked Nov 27 '10 21:11

Gal


People also ask

How do you decrease a for loop in Python?

Use the Reversed Function to Decrement a For Loop in Python The Python reversed() function takes an iterable object, such as a list, and returns a reversed object.

How do you force stop a for loop in Python?

The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.

How do you force stop an infinite loop in Python?

You can stop an infinite loop with CTRL + C .


2 Answers

for n in range(6,0,-1):     print n # prints [6, 5, 4, 3, 2, 1] 
like image 75
Steve Tjoa Avatar answered Oct 02 '22 13:10

Steve Tjoa


This is very late, but I just wanted to add that there is a more elegant way: using reversed

for i in reversed(range(10)):     print i 

gives:

4 3 2 1 0 
like image 41
pratikm Avatar answered Oct 02 '22 14:10

pratikm