Tech With Galvan
Courses/Python Mastery/Control Flow

πŸ§ͺ Practice: Loops & Patterns

35 min β€’ Beginner β€’ Module 6

The classics every coder does: star patterns, multiplication tables, FizzBuzz, and countdowns.

πŸ§ͺ Practice: Loops & Patterns

The legendary workout. Star patterns, multiplication tables, FizzBuzz β€” the exercises every programmer on Earth has done. They look like toys; they build the loop-muscle every real app needs.

Exercise 1 β€” Right triangle of stars

Print (using a nested loop, no hardcoding):

*
* *
* * *
* * * *
* * * * *

Exercise 2 β€” Multiplication table

Ask for a number, print its table from 1 to 10:

Enter a number: 7
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70

Exercise 3 β€” FizzBuzz

Numbers 1 to 30: multiples of 3 print β€œFizz”, multiples of 5 print β€œBuzz”, multiples of both print β€œFizzBuzz”, everything else prints the number.

Exercise 4 β€” Sum until zero

Keep asking for numbers until the user enters 0, then print the total:

Enter a number (0 to stop): 5
Enter a number (0 to stop): 10
Enter a number (0 to stop): 3
Enter a number (0 to stop): 0
Total: 18

Exercise 5 β€” Guess the number

The secret number is 42. Loop until the user guesses it, printing β€œToo high” or β€œToo low” each miss, and the attempt count on success.

Exercise 6 β€” Reverse countdown skip

Print 20 down to 1, but skip multiples of 3 (use continue).

Exercise 7 β€” The pyramid

    *
   ***
  *****
 *******
*********

(Hint: each row prints (5 - row) spaces then (2*row - 1) stars.)


Solutions

Exercise 1:

for row in range(1, 6):
    print("* " * row)

Exercise 2:

num = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{num} x {i} = {num * i}")

Exercise 3:

for n in range(1, 31):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)

Exercise 4:

total = 0
while True:
    num = int(input("Enter a number (0 to stop): "))
    if num == 0:
        break
    total += num
print(f"Total: {total}")

Exercise 5:

secret = 42
attempts = 0

while True:
    guess = int(input("Guess: "))
    attempts += 1
    if guess == secret:
        print(f"Correct! {attempts} attempts")
        break
    elif guess > secret:
        print("Too high")
    else:
        print("Too low")

Exercise 6:

for n in range(20, 0, -1):
    if n % 3 == 0:
        continue
    print(n)

Exercise 7:

for row in range(1, 6):
    spaces = " " * (5 - row)
    stars = "*" * (2 * row - 1)
    print(spaces + stars)

βœ… Module 6 Checkpoint

If you fought through all seven β€” especially the pyramid β€” your loop muscles are real. Every dashboard, leaderboard, and data processor from here on is just these loops wearing nicer clothes.

Next module: Functions β€” packaging your logic so you never write the same block twice.