Python Loop Statements
While programming, we encounter many situations when we need to execute blocks of code repeatedly. So instead of writing those statements again and again we use loops over statements.
Python supports two types of loops: for loop and while.
Python while loop
In the while loop, the while statement condition is checked first and if it returns True, the while clause gets executed.
While loop is the type of the post tested loop where conditional checks in the later first loop have been executed.
If the while statement condition still returns True, then the while clause is executed again. If the test expression is False, the while loop is terminated.
Loop consist the following thing :
- The while keyword
- A condition
- A colon
Block Diagram of while loop
i=0 while(i<=5): print("Hello ! World ") i+=1
Output:
Python 3.8.4 (tags/v3.8.2:7b3ca59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32 ==== RESTART: C:/Users/ASUS/AppData/Local/Programs/Python/Python38-32/df.py ==== Hello ! World Hello ! World Hello ! World Hello ! World Hello ! World Hello ! World
Example 1: Program to find factorial of a number using while loop
n=int(input("Enter Number to find Factorial")) fact=1 i=1 while(i<=n): fact=fact*i i+=1 print("Factorial ",fact)
Output:
Python 3.8.4 (tags/v3.8.2:7b3ca59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32 ==== RESTART: C:/Users/ASUS/AppData/Local/Programs/Python/Python38-32/df.py ==== Enter Number to find Factorial15 Factorial 1307674368000 >>>
Python ‘for’ loop
- For loops in Python corresponds to what are called for-each loops in many other programming languages.
- A for loop acts as an iterator in Python, it goes through each item that is in a collection or any other iterable object.
- for loop is used when we want to iterate over a collection.
- for loop request items one-by-one from a collection/iterable object and assign them in turn to a variable we specify.
- In code, a for statement always consists of the following:
- A variable
- A condition
- A colon
The ‘for’ and ‘in’ keyword
Block Diagram of for loop
for x in range(5): print("Hello! World.")
Output:
Python 3.8.4 (tags/v3.8.2:7b3ca59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32 >>> ================== RESTART: C:/Users/PC/Desktop/Hello.py ================= Hello, world. Hello, world. Hello, world. Hello, world. Hello, world.
Example 1: Write the program to find the table of the given number
n=int(input("Enter Number")) for x in range(1,11): print(n,"*",x,"=",n*x)
Output:
==== RESTART: C:/Users/ASUS/AppData/Local/Programs/Python/Python38-32/df.py ==== Enter Number5 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50 >>>