For Loop In Python

The "for" loop is an iterative statement supported in the Python programming language.

An iterative statment is one which executes one or more statments enclosed in its scope for zero to 'n' number of times.

It is a common requirement in programming to execute a set of statements for multiple times typically for each data element in a collection like an array, list or dictionary.

 

Syntax of Python "for" loop:

for <iterator> in <sequence> : 
    python statement 1
    python statement 2
    python statement 3
    .
    .
    .
    python statement n           
else:
    python statement 1
    python statement 2
    python statement 3
    .
    .
    .
    python statement n  

        

Semantics of Python for loop:

  • Python "forloop takes a sequence object and makes an iterator object out of it
  • For every item in the iterator - or for sake of simplicity - for every item in a sequence, the suite of code followed by the ":" is executed.
  • The else suit of the "for" loop is executed once there are no or no more items in the sequence to iterate over.
  • If a break statement is executed inside the "for" suit, the else suit will not be executed.
  • Python does not support a for loop with takes an index value and works based on the increments or decrements made to the index.
  • If one wants to use a loop based on a increment or decrement counter than the while loop to be used with explicit increment or decrement statements.

Python for loop - Example:

transports = ("Surface Transport", "Air Transport", "Sea Transport")

 

print("For Statement Example:Printing the elements of transport tuple")

for each item in transports:

    print(item)  


Copyright 2019 © pythontic.com