A loop is a control structure that allows a block of code to be executed repeatedly based on a certain condition.
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.
Syntaxfor loop_variable sequence: //statement //statementExample
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.
Noteend=" " is used to remove new line and it generate one whitespace.
we can print the element of string using for loop.
Examplest="Vikas" for i in st: print(i)Output
V i k a s
else keyword is run after the for loop body executed
Examplest="Vikas" for i in st: print(i) else: print("For loop is executed.")Output
V i k a s for loop is executed.
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.
Syntaxwhile condition: //statement //statement incrementation or decrementationExample
x=10 i=0 while i<x: print(i) i=i+1
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.
else keyword is run after the while loop body executed
Examplest="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.