Tuesday, December 3, 2019

Loops in Python

Another one of the control flow statements is loops. 
  • Execute a set of statements that are repeated until a particular condition is satisfied.
  • Loops are used when we want to repeat a block of code to run a number of times.


Basically there are two types of loops in python programming


  1. for loop
  2. while loop 

For loop

For loop is a control flow statement in which the control of the program is continuously transferred to the beginning to execute the body of for loop for a fixed number of times.

Syntax of for loop
                            for a in sequence:
                            body of for
  1. The for loop iterate over a given sequence (it may be list, tuple or string). 
  2. Note: The for loop does not require an indexing variable to set beforehand, as the for command itself allows for this. 

Example
primes = [2, 3, 5, 7] 
for x in primes: 
print(x)

while loop

  • With the help of while loop we can execute a set of statements as long as a condition is true. 
  • It requires to define an indexing variable.

Syntax of While Loop
                while test_expression:
                body of while

Example
To print table of number 2
                        i=2
                        while i<=20:
                        print(i)
                        i+=2

Note:- While other languages contain conditions and increment expression in the syntax of for loop, in Python, the iteration and incremented value are controlled by generating a sequence. 

The range( ) function:

No comments:
Write comments