Lesson 06
while Loop and while..else — Iterative Statements
Write Python while loops with initialization, condition, and updation. Generate number series, multiplication tables, and sums using while..else.
Looping (Iterative / Repetitive) statements
The purpose of looping statements is to perform a certain operation repeatedly for a finite number of times until the test condition becomes false.
Python has 2 types of looping statements:
whileloop ORwhile..elseloopforloop ORfor..elseloop
When you write any loop program, remember 3 points:
| Part | Role |
|---|---|
| Initialization | Where to start |
| Conditional | Where to stop |
| Updation | Increment or decrement |
while loop syntax
while test_condition:
----------------------------------------
indentation block of statements
----------------------------------------
# Other statements in programwhile..else syntax
while test_condition:
----------------------------------------
indentation block of statements
----------------------------------------
else:
----------------------------------------
else block of statements
----------------------------------------
# Other statements in programThe else block runs when the loop exits normally (condition becomes false). It does not run if break terminates the loop.
Example 1 — Generate 1 to n
n = int(input("Enter How Many Numbers u want to Generate:"))
if n <= 0:
print("{} is Invalid input".format(n))
else:
print("-" * 50)
print("Numbers within:{}".format(n))
i = 1 # Initialization Part
while i <= n: # Conditional Part
print(i)
i += 1 # Updation Part
else:
print("*" * 50)Example 2 — Generate n down to 1
n = int(input("Enter How Many Numbers u want to Enter:"))
if n <= 0:
print("{} is Invalid".format(n))
else:
print("=" * 50)
print("Numbers within :{}".format(n))
i = n # Initialization
while i >= 1: # Condition
print("\t\t{}".format(i))
i = i - 1 # Updation
else:
print("=" * 50)Example 3 — Multiplication table
n = int(input("Enter a Number for Generating Mul table:"))
if n <= 0:
print("{} is Invalid Input".format(n))
else:
i = 1
while i <= 10:
print("\t\t{} x {} = {}".format(n, i, n * i))
i += 1
else:
print("=" * 50)Example 4 — Sum of n natural numbers
n = int(input("Enter How Many natural nums u want:"))
if n <= 0:
print("{} is Invalid Input".format(n))
else:
s = 0
i = 1
while i <= n:
print("\t{}".format(i))
s = s + i
i = i + 1
else:
print("sum={}".format(s))Knowledge check
Q1: What three parts must every while loop have?
Answer: Initialization, condition, updation.
Q2: When does while..else run the else block?
Answer: When the loop condition becomes false without break.
Next: File 07 — for Loop
Loading playground…