Python Starter Club

Day - while Loops in Python

Programmer's Picnic - Champak Roy

A while loop repeats a block of code as long as a condition stays True. Useful for repeated input, counters, menus, and loops that stop when the user types exit.

Lesson

1) The basic idea

Read it like: while this condition is True, keep running the block.

while condition:
    # repeated code
Rule: Something inside the loop must change, otherwise you may create an infinite loop.
Examples

2) Counting and sum

Count 1 to 5

i = 1
while i <= 5:
    print(i)
    i += 1

Sum 1 to N

n = int(input("Enter N: "))
i = 1
total = 0
while i <= n:
    total += i
    i += 1
print("Sum =", total)
Flowcharts

3) Visual flow

These show the path the CPU follows in a while loop.

Flow A: entry check

while condition Start Condition? Loop Body Exit True False Repeat

Flow B: update prevents infinite loop

Counter loop i = 1; while i <= 5: print(i); i += 1 Condition uses i Update i (i += 1) If you forget update, i never changes Condition stays True -> infinite loop
Stop Marker
STOP HERE FOR TODAY
If you understand these 3 points, today is complete:
1) while checks condition first
2) loop repeats while condition is True
3) you must update something to stop
MCQ Test

4) while loop MCQs (randomized)

Questions and options randomize every time. Answers and explanations show after submit.

Not submitted
Assignments

5) Practice assignments (do in Python)

  1. Countdown: Input N, print N to 1 using while.
  2. Even Sum: Input N, add only even numbers from 1 to N.
  3. Digits Count: Input a number, count digits using while.
  4. Reverse Number: Input 1234, output 4321 using while.
  5. Menu Loop: Keep showing menu 1) Add 2) Subtract 3) Exit until Exit chosen.
Tip: Try solving in the Pyodide editor below.
Pyodide

6) Run Python here

Write Python code and run it in the browser. If your code uses input(), a prompt will appear.

Pyodide Status: Not loaded
Pyodide needs internet to load. Open this HTML with internet enabled.
Output will appear here...