while loop in Python
Here we will learn how to use the while loop to repeatedly
execute a block of code.
while loop in Python
A while loop is used to repeatedly execute a block of code
as long as a given condition remains True.
Syntax:
while condition:
statements
First, the condition is checked.
If the condition is True, the statements inside the while block are executed.
After executing all the statements in the loop block, the condition is checked again.
This process continues repeatedly until the condition becomes False.
Algorithm to Find the Sum of the First 100 Natural Numbers
Step 1: Start
Step 2: i = 1
Step 3: sum = 0
Step 4: Repeat Steps 5 and 6 while i <= 100
Step 5: sum = sum + i
Step 6: i = i + 1
Step 7: Print sum
Step 8: Stop
Flowchart
Example: Finding the Sum of the First 100 Natural Numbers in Python
# Finding sum of first 100 natural numbers
i = 1
sum = 0
while i <= 100:
sum += i
i += 1
print("Sum:", sum)
Output:
Sum: 5050
Sum: 5050
-
i = 1:
Initializes the variableiwith 1, the first natural number. -
sum = 0:
Initializes the variablesumwith 0 to store the total sum. -
while i <= 100:
The loop continues as long as the value ofiis less than or equal to 100. -
sum += i:
Adds the current value ofitosum. -
i += 1:
Increments the value ofiby 1 after each iteration. -
Loop continues:
Values from 1 to 100 are added tosum. -
print("Sum:", sum):
Prints the final sum.
When to use while loop?
- User-driven loops (for example, run the loop until the user types "exit").
- Reading data from files (reading until End Of File – EOF).
- Waiting for events (for example, rolling a dice until 6 appears).
What We Have Learned So Far
- Learned about the while loop
- Wrote programs using the while loop
- for loop will be covered in the next topic