Python Loops
Loop is a continuous iteration of a block of code to ensure some condition.
It means a group of instructions will execute multiple number of times.
There are following types of loops
Loop Type | Description |
---|---|
while loop | Repeats a statement or group of statements until a given condition is true. It tests the condition before executing the loop body. |
for loop | Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
nested loops | You can use one or more loop inside any another while, for or do..while loop. |
While Loop
Example
x=4 while x>1: print x x--
Output
4 3 2
For Loop
Example
list = [1, 2, 3] for each_num in list print each_num
Output
1 2 3
Loop Control Statements:
Loop control statements change execution from its normal sequence
There are following control statements:
Control Statement | Description |
---|---|
break statement | Terminates the loop statement and transfers execution to the statement immediately following the loop. |
continue statement | Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. |
pass statement | The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. |
for letter in 'scanftree.com': # for loop Example print 'Letter :', letter
In the next chapter you are going to learn python