Day 08.1 - Class Work

Understanding the While Loop in Python

Difference Between For and While Loop

For Loop While Loop
Used when we know the number of iterations in advance. Used when we don’t know the exact number of iterations, loop runs until condition is False.
Iterates over a sequence (list, string, range, etc.). Repeats a block of code based on a condition.
Example:
for i in range(5): print(i)
Example:
i=1
while i<=5:
  print(i)
  i+=1
Stops when the sequence ends. Stops when the condition becomes False.

Syntax of a While Loop

The while loop repeats a block of code as long as the condition is True.

# Basic While Loop syntax
while condition:
    # code to execute
    statement

Flow: Check condition → if True → run code → check again → stop when condition is False.

1. Print Numbers 1 to 5

Simple counting from 1 to 5:

count = 1
while count <= 5:
    print(count)
    count += 1
# Output: 1, 2, 3, 4, 5

2. Sum of Numbers

Calculate sum of numbers from 1 to 5:

total = 0
num = 1
while num <= 5:
    total += num
    num += 1
print(total)
# Output: 15

3. Even Numbers

Print even numbers from 1 to 10:

num = 1
while num <= 10:
    if num % 2 == 0:
        print(num)
    num += 1
# Output: 2, 4, 6, 8, 10

4. Odd Numbers

Print odd numbers from 1 to 10:

num = 1
while num <= 10:
    if num % 2 != 0:
        print(num)
    num += 1
# Output: 1, 3, 5, 7, 9

5. Numbers Greater than 5

Print numbers from 6 to 10:

num = 1
while num <= 10:
    if num > 5:
        print(num)
    num += 1
# Output: 6, 7, 8, 9, 10

6. Numbers Divisible by 3

Print numbers divisible by 3 between 1 and 15:

num = 1
while num <= 15:
    if num % 3 == 0:
        print(num)
    num += 1
# Output: 3, 6, 9, 12, 15

7. Countdown

Print countdown from 5 to 1:

num = 5
while num >= 1:
    print(num)
    num -= 1
# Output: 5, 4, 3, 2, 1

8. Print Stars

Print 5 stars using a while loop:

i = 1
while i <= 5:
    print("*")
    i += 1
# Output: * * * * *

9. Multiplication Table of 2

Print table of 2:

i = 1
while i <= 10:
    print("2 x", i, "=", 2*i)
    i += 1
# Output: 2x1=2, 2x2=4, ..., 2x10=20

10. Repeat a Message

Print "Hello" 5 times:

i = 1
while i <= 5:
    print("Hello")
    i += 1
# Output: Hello (5 times)