Loop in Python

A loop is a control structure that allows a block of code to be executed repeatedly based on a certain condition.

For Loop

In for loop first it check condition and then if the condition is satisfy then its body part is execute and then updation is happen.at last if condition false and loop will terminate.

Syntax
for loop_variable sequence:
    //statement
    //statement
Example
x=10
for i in range(0,x):
    print(i,end=" ")
Output
0 1 2 3 4 5 6 7 8 9 10

In first time at i=0 then it check condition and then if the condition is satisfy then its body part is execute and then updation is happen.at last at x=11 condition false and loop is terminate.

Note

end=" " is used to remove new line and it generate one whitespace.

For loop in string

we can print the element of string using for loop.

Example
st="Vikas"
for i in st:
   print(i)
Output
V
i
k
a
s

for loop with else

else keyword is run after the for loop body executed

Example
st="Vikas"
for i in st:
    print(i)
else:
    print("For loop is executed.")
Output
V
i
k
a
s
for loop is executed.

while loop

In while loop first it checks the condition and body part execute and then updation is happen.At last if condition is false and loop will terminate.

Syntax
while condition:
    //statement
    //statement
    incrementation or decrementation
Example
x=10
i=0
while i<x:
    print(i)
    i=i+1

Output

0 1 2 3 4 5 6 7 8 9 10
Here the initially x=10 and i=0 first it check the condition and then body part execute then updation is happen.At last at i=11 condition is false and loop will terminate. 

while loop with else

else keyword is run after the while loop body executed

Example
st="Vikas"
i=0
while i<len(st):
    print(st[i])
    i=i+1
else:
    print("For loop is executed.")
Output
V
i
k
a
s
for loop is executed.