Loops are a basic, but essential part of Python, amongst other programming languages. They are used to execute a block of code a specified number of times. Loops are classified into two types: while loops and for loops, each having its own use.
For Loops[]
For loops are used to iterate over a sequence of characters/items, or iterables, like lists, tuples, dictionaries, or even a range of numbers.
Syntax[]
for variable in sequence:
expression
Example:
for i in xrange(1, 3):
print(i)
Output:
1 2 3
Nested For Loops[]
A nested for loop is a loop that is inside of another for loop.
Syntax[]
for variable in sequence:
for second_variable in second_sequence:
expression
Example:
for i in xrange(1, 3):
for j in xrange(i, 4):
print(i, j)
Else Statements[]
An else statement is used to execute a block of code after the for loop ends completely without any interruption, i.e. if the break statement is not used.
Syntax[]
for variable in sequence:
expression
else:
ending_condition
Example:
for i in xrange(1, 3):
print(i)
else:
print("after for")
Output:
1 2 3 after for
While Loops[]
A while loop is a control flow statement that allows the execution of its block of code, as long as the specified boolean condition in the same line of the while keyword evaluates to True.
Loop control statements[]
Loop control statements change standard loop execution flow.
while result = do_something():
print result
Execution of this loop is stopped do_something() returns False
break[]
The break statement is the statement used to stop the loop before it finishes.
for i in (1, 2, 3):
if i == 2:
break
print i
print 'test'
Output:
1 test
continue[]
The continue statement is the statement used to stop the current iteration and return back to the start of the loop.
for i in (1, 2, 3):
if i == 2:
continue
print i
print 'test'
Output:
1 3 test
pass[]
The pass statement is a statement that is used as a placeholder for if there's nothing to add in the block of code inside a while loop or a for loop.
for i in (1, 2, 3):
pass
Output:
(empty output)