CodeSutraHub

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

while loop 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
  1. i = 1:
    Initializes the variable i with 1, the first natural number.
  2. sum = 0:
    Initializes the variable sum with 0 to store the total sum.
  3. while i <= 100:
    The loop continues as long as the value of i is less than or equal to 100.
  4. sum += i:
    Adds the current value of i to sum.
  5. i += 1:
    Increments the value of i by 1 after each iteration.
  6. Loop continues:
    Values from 1 to 100 are added to sum.
  7. 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
We will also learn about do-while in the next topic.

Below Video Explains while Loop in Python