This page topics close

Loop statement is used to repeat the statements N number of times.

It has the ability to iterate over the items of any sequence, such as a list or a string.

The for statement in Python differs a bit from what you may be used to in C or Java. Rather than giving the user the ability to define both the iteration step and halting condition (as C), Python?s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

  • Syntax of Loop

    for iterating_var in sequence:
                 statements(s) 

  • The range() Function

    If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions

    Example)
    drag_handle
     
    # Example of range() function 
    seq=range(5) 
    for n in seq:
    	print(n)
    
    # save file anyname.py
    # open cmd and type : python anyname.py
    Output:
    0
    1
    2
    3
    4

    The given end point in range function always excluded. range(5) : generates sequence of 1 to 4


    Example: range(start, end)

    
    # Example of range(start, end) function 
    for i in range(1,6):
    	print(i)
    
    # save file anyname.py
    # open cmd and type : python anyname.py

    Output:
    1
    2
    3
    4
    5
    

    Example: printing the elements of list

    
    # printing the elements of list
    list=['java','python','php','dotnet']
    for x in list:
    	print(x)

    Output:
    java
    python
    php
    dotnet

    Example : print the numbers in reverse order

    # printing the number in reverse order
    print(list(range(10)))
    for i in  range(10,0,-1):
    	print(i)

    Output:
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    10
    9
    8
    7
    6
    5
    4
    3
    2
    1

    -1 in 3rd argument in range is used to change the direction of loop

Important Point about range () function

In many ways the object returned by range() behaves as if it is a list, but in fact it isn?t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn?t really make the list, thus saving space.

What next?

Share this page