Day 08.0 - Class Work

Understanding For Loop in Python

What is a For Loop?

A for loop is used to repeat a block of code multiple times. It goes through each item in a sequence (like a list, word, or range of numbers).

# Basic For Loop Syntax
for item in sequence:
    # code to run
    print(item)

Here, item is a variable that takes each value from the sequence one by one.

The "in" Keyword

The keyword in is used to check each element inside a sequence. For example, when we say for x in fruits:, Python will go one by one through the fruits list.

fruits = ["apple", "banana", "cherry"]
for x in fruits:
    print(x)

# Output:
# apple
# banana
# cherry

The range() Function

The range() function generates a sequence of numbers.
range(n) gives numbers from 0 to n-1.
range(start, stop) gives numbers from start to stop-1.
range(start, stop, step) gives numbers with jumps (step).

for i in range(5):
    print(i)

# Output:
# 0
# 1
# 2
# 3
# 4

1. Print Numbers from 0 to 4

for i in range(5):
    print(i)

# Output:
# 0
# 1
# 2
# 3
# 4

2. Print Each Fruit

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Output:
# apple
# banana
# cherry

3. Print Hello 5 Times

for i in range(5):
    print("Hello")

# Output:
# Hello
# Hello
# Hello
# Hello
# Hello

4. Sum of Numbers

numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
    total += num
print(total)

# Output:
# 15

5. Print Even Numbers

for num in range(10):
    if num % 2 == 0:
        print(num)

# Output:
# 0
# 2
# 4
# 6
# 8

6. Print Odd Numbers

for num in range(10):
    if num % 2 != 0:
        print(num)

# Output:
# 1
# 3
# 5
# 7
# 9

7. Numbers Greater than 5

for num in range(10):
    if num > 5:
        print(num)

# Output:
# 6
# 7
# 8
# 9

8. Numbers Divisible by 3

for num in range(10):
    if num % 3 == 0:
        print(num)

# Output:
# 0
# 3
# 6
# 9

9. Print Each Letter in a Word

word = "Python"
for letter in word:
    print(letter)

# Output:
# P
# y
# t
# h
# o
# n

10. Print Squares of Numbers

for num in range(1, 6):
    print(num * num)

# Output:
# 1
# 4
# 9
# 16
# 25

11. Print Numbers in Reverse

for num in range(5, 0, -1):
    print(num)

# Output:
# 5
# 4
# 3
# 2
# 1

12. Multiplication Table of 2

for i in range(1, 11):
    print("2 x", i, "=", 2*i)

# Output:
# 2 x 1 = 2
# 2 x 2 = 4
# ...
# 2 x 10 = 20

13. Numbers with Step 2

for i in range(0, 10, 2):
    print(i)

# Output:
# 0
# 2
# 4
# 6
# 8

14. Print Name 3 Times

for i in range(3):
    print("Alice")

# Output:
# Alice
# Alice
# Alice

15. First 5 Natural Numbers

for i in range(1, 6):
    print(i)

# Output:
# 1
# 2
# 3
# 4
# 5