user2010736
user2010736

Reputation:

Python for loop equavalent to C

I'm new to python and i can't figure out how to write a reverse for loop in python.

e.g. the python equivalent to the C lang loop

for (i = 10; i >= 0; --i) {
    printf ("%d\n", i);
}

Upvotes: 1

Views: 183

Answers (4)

MangeshBiradar
MangeshBiradar

Reputation: 3938

You can use python range method.

for loop in python equavalent to C will be:

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

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599778

As Pavel mentions, you rarely need indexed loops. For those occasions you do, though, there's enumerate:

for i, element in enumerate(sequence):
    print '%s is in index %d' % (element, i)

Upvotes: 0

gefei
gefei

Reputation: 19816

try this for i in range(10,-1,-1)

Upvotes: 0

Pavel Anossov
Pavel Anossov

Reputation: 62928

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

You rarely need indexed loops in Python though.

Usually you're iterating over some sequence:

for element in sequence:
   do_stuff(element)

To do this in reverse:

for element in reversed(sequence):
   do_stuff(element)

Upvotes: 11

Related Questions