Control Flow

For Loop in Python

The for loop is used to iterate through a sequence. When a range is provided as the sequence, it behaves like a C-style for loop. For all other sequences (arrays, etc.), it behaves like a for each loop.


Syntax
# for-each behaviour
for element in sequence:
    #code to perform, on element

# C-style for loop behaviour, start index is optional
for element in range(start, finish):
   #code to execute

Notes

A sequence can be a list, set, or range.

The control structure takes an element from the sequence and executes the statements. It then continues to do the same on subsequent elements until there are no more elements in the sequence.

Iteration through a range is done in numerical order. Iteration through a non-range sequence has no guarantee of order.


Example
grades = [85, 95, 80]

for grade in grades:
    print ("Student grade: {}".format(grade))

< If Statement   |   While Loop >

© 2019 SyntaxDB. All Rights Reserved.