Loop STATEMENTS
The Loop statements allow a set of instructions to be performed repeatedly until a certain condition is fulfilled. The iteration statements are also called loops or looping statements.
THE FOR LOOP
The for loop is the easiest to understand of the python loops.
Syntax:
For I in range(lowerlimit,upperlimit):
Loop Body
The program will run until I value becomes equal to upperlimit – 1.
Example:
For I in range(1,5):
Print(“Hello”)
This program will print Hello 4 times, ie from 1 to 4 (upper limit-1)
I value will start as 1 then loop body will get executed and I value will be incremented. This keeps on taking place until I ==upper limit-1 . After that
the program comes out of loop body.
THE WHILE LOOP
The second loop available in python is the while loop. The while loop is an entry controlled loop.
The syntax of a while loop is
while (expression):
Loop-body
Where loop body keep on getting executed until the expression becomes false. When the expression becomes false, the program control passes to
the line after the loop-body code.
When to use FOR LOOP?
FOR LOOP is appropriate when you know in advance how many times loops will be executed
When to use WHILE LOOP?
WHILE loop should be preferred when you don’t know how many times
the loop will be executed.
Download Python Learning app from APK Monster Z
Comments
Post a Comment