Python Loops

What is a Loop?

A loop is a sequence or order of instructions that are frequently repeated until a certain condition reached.

Types of loops in Python:

1.for loop




2.while loop

3.nested loop

for loop:

for( i =0;i<n;i++) —–> Which is not implemented in Python

>>> for i range(3)
>>>print(i)
Output: 
0
1
2
3
>>> for i in range(1,4)
>>>print(i)
1
2
3

Examples:

for_example_demo.py

1. To do the operation on each and every element of a list

a=[1,2,3,4,5]
b=0
for i in a;
b=b+i
print(b)

2.Return to list

a=[1,2,3,4,5]
for i in a;
print(i**2)
b=[(i**2)for i in a]
print(b)

for with if:

student_marks = [10,36,53,28,90]
for data in student_marks:
                if(data%2==0)
                       print(data, "is even number")
                else:
                       print(data,"is odd number")

for loop with else clause:

numbers = [10,20,30,40,50,60]
for i in numbers:
            print(i)
else:
           print("Loop completed ")

Looping control statement: A statement that converts the execution of loop from its designated cycle is called a loop control statement. The best example is the Break.

Break:

To break out the loop we can use a break function

syntax:

for variablie_name in sequence:

statement1

statement2

if(condition):

break

Example

>>>list = [10,20,30,40,50]
>>>for i in list:
            if(i==40)
                break
          print(i)

Continue statement:

Continue statement is used, Python to jump to the next iteration of a loop.

Example:
list = [10,20,30,40,50]
for i in list:
         if(i==40)
                continue
                 print(i)
          else:
             print("completed")

While Loop:

While loop is used to execute no.of statements till the condition passed in while loop once a condition is false, the control will come out the loop.



syntax:

while<expression>:

statement1

statement2

>>>while(i<n):
     print(i)

infinite loop

while else loop:

a =int(input("Enter integer less 100\n"))
print(a)

Summary: In Python programming language loops are very useful while using programs. In Loops will improve our logical thinking also. Python loops are very simple to learn and improve. Here only tell to for loop and while because these two are a major role in loops environment in Python Programming language