Courses/Python Mastery/Module 6: Control Flow
Module 6 ยท Lesson 535 minBeginner๐Ÿงช Practice Session

๐Ÿงช Practice: Loops & Patterns

Lesson goal
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):

code
*
* *
* * *
* * * *
* * * * *

Exercise 2 โ€” Multiplication table

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

code
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:

code
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

code
*
   ***
  *****
 *******
*********

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


Solutions

Exercise 1:

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

Exercise 2:

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

Exercise 3:

code
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:

code
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:

code
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:

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

Exercise 7:

code
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.