Related chapter: Control Flow

Exercise 1: Grade Calculator

Write a function that converts a score (0–100) to a letter grade:

Score Grade
90–100 A
80–89 B
70–79 C
60–69 D
0–59 F

Use elif chains. Test with 95, 82, 71, 55.

Exercise 2: Sum of Range

Write a function sum_range(start, end) that returns the sum of all integers from start to end (inclusive) without using sum(range()).

  sum_range(1, 5)   # 15
sum_range(10, 13) # 46
  

Exercise 3: Prime Checker

Write is_prime(n) that returns True if n is a prime number.

  is_prime(17)  # True
is_prime(15)  # False
is_prime(2)   # True
is_prime(1)   # False
  
Hint

Check divisibility from 2 to int(n**0.5) + 1.

Exercise 4: Multiplication Table

Print a formatted multiplication table for 1–10:

     1   2   3   4   5 ...
   2   4   6   8  10
   3   6   9  12  15
  

Use nested loops and string formatting for alignment.

Exercise 5: List Comprehension Challenges

Create these using list comprehensions only (no loops):

  # Squares of even numbers 0–20
# [0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

# Words longer than 3 chars, uppercased
words = ["I", "love", "Python", "code", "AI"]
# ['LOVE', 'PYTHON', 'CODE']

# Flatten a matrix
matrix = [[1, 2], [3, 4], [5, 6]]
# [1, 2, 3, 4, 5, 6]
  

Exercise 6: Guess the Number

Write a number guessing game:

  1. Pick a random number 1–100
  2. Ask the user to guess
  3. Reply “too high” or “too low”
  4. Count attempts and congratulate on success
  import random
secret = random.randint(1, 100)
# ... your code
  

Challenge: Diamond Pattern

Print a diamond of stars for odd n:

  n = 5:
  *
 ***
*****
 ***
  *
  

Use nested loops. Bonus: solve with a single list comprehension per row.

Solution (Exercise 3)
  def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True
  

Exercise 7: Collatz Sequence

Print the Collatz sequence starting from n until reaching 1:

  # collatz(6) prints: 6 3 10 5 16 8 4 2 1
# Rule: if even → n/2, if odd → 3n+1
  

Exercise 8: Pascal’s Triangle

Print the first n rows of Pascal’s triangle:

  n = 5:
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1
  
Hint

Each row starts and ends with 1. Inner values are the sum of the two values above.

Next: Functions Exercises