for loop in Python

 

For Loop in Python

 

Loop statements in Python

What is Loop/ Iteration: 

Loop is used to execute a single statement or set of statements (Block of statements) again and again until condition does not satisfy. These statements are also called iterative statements. 

For example suppose you want to display 25 numbers starting from 1, in one instruction until last number i.e26 will not get and  the  instruction will  execute  again  and  again  and  in each  repetition the number will be increased by one. once  get  26th number then the iteration  will  stop  and  display all numbers. 

for Loop in Python :       

The for loop is used to iterate the objects in sequence for example lists, tuples and string. 

Syntax:

for val in sequence:
            loop body

val is the variable which takes the value of objects inside the sequence on each iteration. This loop will iterates until we do not reach the last object in the sequence.

 

Example

# Demonstration of for loop

# Sum of all objects in List

list1=[1,2,3,4,5,6,7,8,9,10

sum=0

print(" List objects are:\n ",list1)

print("Sum of all List objects is:\n ")

for i in list1:

    sum = sum + i 

    

    print(sum)

 

o/p:

List objects are:

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

Sum of all List objects is:

 

1

3

6

10

15

21

28

36

45

55

 

Another example to demonstrate for loop

# Sum of all even objects in list

list1=[1,2,3,4,5,6,7,8,9,10

sum=0

print(" List objects are:\n ",list1)

print("Sum of all even List objects is:\n ")

for i in list1:

    if i%2==0:

        sum = sum + i 

        print(sum)

o/p:

 

 List objects are:

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

Sum of all even List objects is:

 

2

6

12

20

30

 

        

 

 

टिप्पणी पोस्ट करा

1 टिप्पण्या

कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏