Python looping statement
This tutorial is a Python looping statement. A looping statement is used in the programming language that allows us to repeat a block of the code a number of times.
Python has two types of loops available:
- While loop
- For loop
You can also specify else block with looping statement.
While
while loop executes a block of code until the specified condition is true otherwise
terminate the loop.
Syntax
while expression :
# statement
Example
year = 2001 while year <= 2005 : print("Year :",year) year+=1 Output: Year : 2001 Year : 2002 Year : 2003 Year : 2004 Year : 2005
While else
else block executes only when the loop terminates normally not by a break statement.
Syntax
while expression :
# statement
else:
# else statement
Example
year = 2001 while year <= 2005 : print(year) year+=1 else: print("year is no longer less than 2006") Output: 2001 2002 2003 2004 2005 year is no longer less than 2006
For
For loop mostly used for looping over sequences list, tuple, dictionary. for loop executes it stores the first item in loop variable and execute the block code until the sequence is not empty.
Syntax
for variable in sequence :
# statement
Example
years = [2001,2002,2003,2004,2005] for year in years : print("Year :",year) Output: Year : 2001 Year : 2002 Year : 2003 Year : 2004 Year : 2005
For else
for else executes when loop terminates normally not by using break statement.
Syntax
for variable in sequence :
# statement
else:
# else statement
Example
years = [2001,2002,2003,2004,2005] for year in years : print("Year :",year) else: print("Years is empty") Output: Year : 2001 Year : 2002 Year : 2003 Year : 2004 Year : 2005 Years is empty