For Loop in Python


 For Loop

   For, loop in Python is used to execute a block of statements or code several times until the given condition is becomes false. It is better to use for loop if the number of iteration is known in advance.

It is frequently used to traverse the data structures like list, tuple, or dictionary.

Syntax

The syntax of for loop in python is given below.

  1. for variable in sequence:    
  2.     statement(s)         # body of for loop

Here variable will take the value from the sequence and execute it until all the values in the sequence are done.

Flow Chart 



Example 

language=["python","java","ruby"]

for lang in language:
     
        print("current language is :", lang)

Output 

current language is : python

current language is : java

current language is : ruby

In Python there is no C style for loop means for(i=0;i<n;i++). There is "for in" loop which is similar to for each loop in other languages.

With the for loop we can execute a set of statements. Once for each item in a list, tuple, set etc.

A for loop is used for iterating over a list, a tuple, a dictionary, a set or a string.

Example :

# Iterating over a list

print("list iteration")

l=["technical","gupta","ji"]

for i in l:

        print(i)

# Iterating over a tuple

print("tuple iteration")

t=("btech","second","year")

for i in t:

         print(i)

# Iterating over a string

print("string iteration")

s= "Python"

for i in s:

         print(i)

Output 

list iteration

technical 
gupta
ji

tuple iteration

btech
second 
year

string iteration

p
y
t
h
o
n

For loop using range () function

    The range() function is used to generate a sequence of numbers. For example if we pass the range(5), it will generate the numbers for 0 to 4 (5 numbers).The syntax of the range() function is given below.

Note : The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter. for example range(2,6), which means values from 0 to 6 (but not including 6).

Syntax

range(start,stop,step,size)

  • The start represents the beginning of the iteration.
  • The stop represents that the loop will iterate till stop-1. The range(1,5) will generate numbers 1 to 4 iterations. It is optional.
  • The step size is used to skip the specific numbers from the iteration. It is optional to use. By default, the step size is 1. It is optional.

Example

for i in range(5):
        
       print(i)

Output

0
1
2
3
4
    

Else statement with for loop

     We can also combine else statement with for loop. But as there is no condition in for loop based on which will be executed immediately after for block finishes execution.

Example

list=["python","for","btech"]

for index in range(len(list)):

          print(list[index])
else:
          print("inside else block")

Output

python
for 
btech

inside else block












No comments:

Post a Comment