Newby Coder header banner

Python Loops

Python For Loop

for loop in Python can be used to iterate over a sequence (list, tuple, string) or other iterable objects

It allows to execute one or more statements for each item of the sequence

Example

Print each fruit in a fruit list

fruits = ["lemon", "orange", "melon"]
for x in fruits:
    print(x) 

Output

lemon
orange
melon

Alternatively, indexes can be used to derive the same

fruits = ["lemon", "orange", "melon"]
for x in range(0, len(fruits)):
    print(fruits[x]) 

Above code uses len() function to get size of fruits list

and range() function to get integer values from 0 to (excluding) size of the list

These values are then used as indexes to retrieve items from fruits list

Syntax of Python for Loop

for item in sequence:
    Body of for 

Here, item is a variable that takes the value of the corresponding item of a sequence for each iteration

Loop continues until last item in the sequence, unless break statement is used (or statements like System.exit())

The body of for loop is supposed to be indented (with spaces or tabs), otherwise it throws error

Python uses indentation as its method of grouping statements

In Python, all the statements indented by the same number of space characters are considered to be part of a single block of code

More about indentation

Python while Loop

A while loop statement in Python programming language repeatedly executes a target statement(or block of statements) as long as a given condition is true

Syntax

The syntax of a while loop is -

while code:
   statement(s) 

Here, statement(s) may be a single statement or a block of statements

condition may be any expression, which is evaluated and the loop iterates if it is True

Any non-zero value is also considered as true

When the condition is tested and the result is false, the loop body is skipped and the first statement after the while loop is executed

While loop might not ever run, in case the condition is initially False

Example

#!/usr/bin/python

count = 0
while(count <9):
    print('The count is:', count)
    count = count +1 

When above code is executed, it produces following result

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8 

In above example an indexing variable count is defined which is set to 0

The block consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9

With each iteration, the value of the index count is displayed and then increased by 1

Python break Statement

With a break statement, a loop can be stopped during its iteration

Example

Following example uses break to exit a while loop when value of i is 3:

i = 1
while i < 6:
    print(i)
    if i == 3:
        break
    i += 1 

Example

With a break statement, a loop can be stopped before it has looped through all the items

Exit the loop when x is "orange":

fruits = ["lemon", "orange", "melon"]
for x in fruits:
    print(x)
    if x == "orange":
        break 

Looping Through a String in Python

In Python, Strings are iterable objects, which contain a sequence of characters

Example

Looping through the letters in the word "bazinga":

for x in "bazinga":
    print(x)
Output
b
a
z
i
n
g
a 

Python range() function

range() function can be used to retrieve a sequence of numbers or to loop through a set of code for a specified number of times

range(10) generates numbers from 0 to 9 (10 numbers)

The start, stop and step size can also be defined as range(start, stop, step size)

If a single argument is provided, it is taken as the value of stop parameter, which decides the last value of the sequence

start is 0 by default and step size defaults to 1 if not provided

Example

print from 1 to 5 using range() function:

>>> for x in range(6):
...    print(x)
...
0
1
2
3
4
5
  • range(6) is not the values of 0 to 6, but the values 0 to 5

  • The starting value can be specified by adding a parameter like range(2, 6) which returns values from 2 to 6 (excluding 6)

    >>> for x in range(2, 6):
    ...     print(x)
    ...
    2
    3
    4
    5 

    Example using step size as 3

    >>> for x in range(2, 20, 3):
    ...     print(x)
    ...
    2
    5
    8
    11
    14
    17

    range function does not store all the values in memory but generates the next number on the go

    To force this function to output all the items, the list() function can be used

    >>> range(3, 8)
    range(3, 8)
    >>> list(range(3, 8))
    [3, 4, 5, 6, 7]

    Python Infinite Loop

    A loop becomes infinite loop if a condition never becomes False

    This results in a loop that never ends

    It can be as a result of human error

    An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required

    #!/usr/bin/python
    var=1
    while var==1: # This constructs an infinite loop, assuming value of var is not changed
        num = raw_input("Enter a number :")
        print(num, "is entered")
    print("Unreachable") 

    Above code can be executed as :

    Enter a number  :20
    20 is entered
    Enter a number  :29
    29 is entered
    Enter a number  :3
    3 is entered
    Enter a number :Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
    KeyboardInterrupt 

    Since above example goes in an infinite loop, the program has to be exited explicitly (using CTRL+C etc)

    Python continue Statement

    continue statement is used to proceed to next iteration of a loop, without executing any further statement(s) of current iteration

    Example

    Continue to the next iteration if i is 3:

    i = 0
    while i < 7:
        i += 1 
        if i in [2, 5]:
            continue
        print(i) 

    This produces following output

    1
    3
    4
    6
    7 

    Example

    Do not print orange :

    fruits = ["lemon", "orange", "melon"]
    for x in fruits:
        if x is "orange":
            continue
        print(x) 
    Output
    lemon
    melon

    It is used when one or more statements are to be omitted for specified conditions while iterating

    Python pass Statement

    The pass statement is a null operation; nothing happens when it executes

    pass is of use in places where code is unimplemented (skeleton code) since, after a conditional statement at least one statement is required in an indented block

    Syntax

    pass 

    Example

    #!/usr/bin/python
    for letter in 'Python':
        if letter =='h':
            pass
            print('This is pass block')
        print('Current Letter :',letter) 
    Output
    Current Letter : P
    Current Letter : y
    Current Letter : t
    This is pass block
    Current Letter : h
    Current Letter : o
    Current Letter : n 

    Using else Statement with Loops

    Python supports an else statement associated with a loop statement

    else with while loop

    Following example uses an else statement with a while statement that prints a number as long as it is less than 5, otherwise else statement gets executed

    #!/usr/bin/python
    
    count = 0
    while count<5:
        print(count, "is less than 5")
        count = count + 1
    else:
        print(count," is not less than 5") 

    When above code is executed, it produces following result -

    0 is less than 5
    1 is less than 5
    2 is less than 5
    3 is less than 5
    4 is less than 5
    5 is not less than 5 

    else with for loop

    A for loop can also have an optional else block

    The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

    In case a break statement is used to stop a for loop, the else part is ignored

    Example

    Print all numbers from 0 to 5, and print a message when the loop has ended:

    for x in range(6):
        print(x)
    else:
        print("Out of range") 

    Output

    0
    1
    2
    3
    4
    5
    Out of range