Loops in Python Language is used to repeat a block of code for several times until a specific result is obtained. Suppose you have to print your name several times, instead of printing multiple lines you can use loops. Python has two types of loops.
- While Loop
- For Loop
The While Loop in Python
The while loop is a condition-controlled loop, it means it will repeat until a specific condition is met. The statements which you want to repeat must be indented, after a while condition.
Syntax:
while condition:
#statement
#statement
Example 1: Python program to print 1 to 10.
n=1
while n<=10:
print(n)
n=n+1
The above program will print 1 to 10 as output. An initial value of a variable n is 1, the value of n is less than 10, so the condition is true, after that it prints the value of n, after that increase the value by 1. Every time it checks the condition and repeats the statements until the condition is not false.
Example 2: Python program to print your name 10 times.
n=1
while n<=10:
print("Python Programming")
n=n+1
Example 3: Python program to print 1 to 10 in the same line.
n=1
while n<=10:
print(n,end='\t')
n=n+1
Python While with Else Statement
We can also use else statement with the loop in Python, when the loop condition is false, then else block will execute. If a break statement is executed in the loop block, then else part will be skipped.
Example 4: Python program to calculate the sum of 1 to 10.
n=1
s=0
while n<=10:
s=s+n
n=n+1
else:
print("Sum :",s)
Use of If-Else Within While Block.
We can also use if and else condition within while loop as a statement.
Example 5: Python program to accept numbers and calculate the sum of even numbers only.
n=1
s=0
while n<=10:
i=int(input("Enter a number"))
if i%2==0:
s=s+i
n=n+1
else:
print("Sum :",s)