python

exercises

exercises.pyšŸ
"""
03 - Control Flow: Exercises
Practice conditions and loops!
"""

print("=" * 60)
print("CONTROL FLOW - EXERCISES")
print("=" * 60)

# =============================================================================
# EXERCISE 1: Age Category
# =============================================================================
print("\n--- Exercise 1: Age Category ---")

# Given age, determine the category:
# - 0-12: Child
# - 13-19: Teenager
# - 20-59: Adult
# - 60+: Senior

age = 25

# Your code here:
category = None

# print(f"Age {age} is a {category}")

# =============================================================================
# EXERCISE 2: Number Analysis
# =============================================================================
print("\n--- Exercise 2: Number Analysis ---")

# Given a number, determine:
# - Is it positive, negative, or zero?
# - Is it even or odd?
# - Is it a multiple of 5?

number = 15

# Your code here:
sign = None        # "positive", "negative", or "zero"
parity = None      # "even" or "odd"
mult_of_5 = None   # True or False

# print(f"Number {number}: {sign}, {parity}, multiple of 5: {mult_of_5}")

# =============================================================================
# EXERCISE 3: Sum of Numbers
# =============================================================================
print("\n--- Exercise 3: Sum of Numbers ---")

# Using a for loop, calculate the sum of numbers from 1 to 100

# Your code here:
total = None

# print(f"Sum of 1 to 100: {total}")  # Should be 5050

# =============================================================================
# EXERCISE 4: Factorial
# =============================================================================
print("\n--- Exercise 4: Factorial ---")

# Calculate the factorial of n (n!)
# Example: 5! = 5 Ɨ 4 Ɨ 3 Ɨ 2 Ɨ 1 = 120

n = 5

# Your code here:
factorial = None

# print(f"{n}! = {factorial}")  # Should be 120

# =============================================================================
# EXERCISE 5: Count Vowels
# =============================================================================
print("\n--- Exercise 5: Count Vowels ---")

# Count the number of vowels in the string

text = "Hello World Python Programming"

# Your code here:
vowel_count = None

# print(f"Vowels in '{text}': {vowel_count}")  # Should be 7

# =============================================================================
# EXERCISE 6: Find Maximum
# =============================================================================
print("\n--- Exercise 6: Find Maximum ---")

# Find the maximum number in the list WITHOUT using max()

numbers = [23, 45, 12, 89, 34, 67, 90, 21]

# Your code here:
maximum = None

# print(f"Maximum in {numbers}: {maximum}")  # Should be 90

# =============================================================================
# EXERCISE 7: Reverse a List
# =============================================================================
print("\n--- Exercise 7: Reverse a List ---")

# Reverse the list using a loop (not slicing or reverse())

original = [1, 2, 3, 4, 5]

# Your code here:
reversed_list = None

# print(f"Original: {original}")
# print(f"Reversed: {reversed_list}")  # Should be [5, 4, 3, 2, 1]

# =============================================================================
# EXERCISE 8: List Comprehension Practice
# =============================================================================
print("\n--- Exercise 8: List Comprehension ---")

# Create these lists using list comprehension:

# a) Squares of numbers 1-10
squares = None

# b) Even numbers from 1-20
evens = None

# c) Numbers divisible by 3 from 1-30
div_by_3 = None

# d) First letter of each word (uppercase)
words = ["apple", "banana", "cherry", "date"]
first_letters = None

# print(f"Squares: {squares}")       # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# print(f"Evens: {evens}")           # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# print(f"Div by 3: {div_by_3}")     # [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
# print(f"First letters: {first_letters}")  # ['A', 'B', 'C', 'D']

# =============================================================================
# EXERCISE 9: Guess the Number
# =============================================================================
print("\n--- Exercise 9: Guess the Number ---")

# Write a while loop that simulates a guessing game
# The secret number is 7
# Keep asking until the user guesses correctly
# (For testing, we'll simulate guesses)

secret = 7
guesses = [3, 5, 7]  # Simulated guesses
attempt = 0
found = False

# Your code here: (use the guesses list instead of input)
# Hint: use while and break

# print(f"Found the number in {attempt} attempts!")

# =============================================================================
# EXERCISE 10: Prime Number Checker
# =============================================================================
print("\n--- Exercise 10: Prime Checker ---")

# Write a function to check if a number is prime

def is_prime(n):
    """Return True if n is prime, False otherwise."""
    # Your code here:
    pass

# Test cases:
# print(is_prime(2))   # True
# print(is_prime(7))   # True
# print(is_prime(10))  # False
# print(is_prime(17))  # True
# print(is_prime(1))   # False

# =============================================================================
# EXERCISE 11: FizzBuzz
# =============================================================================
print("\n--- Exercise 11: FizzBuzz ---")

# Print numbers 1-30, but:
# - For multiples of 3, print "Fizz"
# - For multiples of 5, print "Buzz"
# - For multiples of both 3 and 5, print "FizzBuzz"

# Your code here:
fizzbuzz_result = []

# print(fizzbuzz_result)

# =============================================================================
# EXERCISE 12: Dictionary Comprehension
# =============================================================================
print("\n--- Exercise 12: Dictionary Comprehension ---")

# Create these dictionaries using comprehension:

# a) Number and its cube: {1: 1, 2: 8, 3: 27, ...} for 1-5
cubes = None

# b) Word and its length: {'hello': 5, 'world': 5, ...}
words = ["hello", "world", "python", "code"]
word_lengths = None

# c) Filter: only even numbers and their squares
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = None

# print(f"Cubes: {cubes}")
# print(f"Word lengths: {word_lengths}")
# print(f"Even squares: {even_squares}")

# =============================================================================
# EXERCISE 13: Nested Loop Pattern
# =============================================================================
print("\n--- Exercise 13: Pattern Printing ---")

# Print this pattern:
# *
# **
# ***
# ****
# *****

# Your code here:

# Then print inverted:
# *****
# ****
# ***
# **
# *

# Your code here:

# =============================================================================
# EXERCISE 14: Number Pyramid
# =============================================================================
print("\n--- Exercise 14: Number Pyramid ---")

# Print this pattern:
# 1
# 12
# 123
# 1234
# 12345

# Your code here:

# =============================================================================
# EXERCISE 15: Password Validator
# =============================================================================
print("\n--- Exercise 15: Password Validator ---")

def validate_password(password):
    """
    Validate password against these rules:
    - At least 8 characters
    - Contains at least one uppercase letter
    - Contains at least one lowercase letter
    - Contains at least one digit
    - Contains at least one special character (!@#$%^&*)
    
    Return a tuple: (is_valid, list_of_failures)
    """
    # Your code here:
    pass

# Test:
# print(validate_password("Abc123!@"))  # (True, [])
# print(validate_password("abc"))  # (False, ['too short', 'no uppercase', 'no digit', 'no special'])

# =============================================================================
# SOLUTIONS
# =============================================================================
print("\n" + "=" * 60)
print("SOLUTIONS (scroll down after trying!)")
print("=" * 60)

"""
EXERCISE 1:
if age < 13:
    category = "Child"
elif age < 20:
    category = "Teenager"
elif age < 60:
    category = "Adult"
else:
    category = "Senior"

EXERCISE 2:
sign = "positive" if number > 0 else "negative" if number < 0 else "zero"
parity = "even" if number % 2 == 0 else "odd"
mult_of_5 = number % 5 == 0

EXERCISE 3:
total = 0
for i in range(1, 101):
    total += i
# Or: total = sum(range(1, 101))

EXERCISE 4:
factorial = 1
for i in range(1, n + 1):
    factorial *= i

EXERCISE 5:
vowels = "aeiouAEIOU"
vowel_count = 0
for char in text:
    if char in vowels:
        vowel_count += 1
# Or: vowel_count = sum(1 for c in text if c in vowels)

EXERCISE 6:
maximum = numbers[0]
for num in numbers[1:]:
    if num > maximum:
        maximum = num

EXERCISE 7:
reversed_list = []
for i in range(len(original) - 1, -1, -1):
    reversed_list.append(original[i])
# Or using while:
# i = len(original) - 1
# while i >= 0:
#     reversed_list.append(original[i])
#     i -= 1

EXERCISE 8:
squares = [x**2 for x in range(1, 11)]
evens = [x for x in range(1, 21) if x % 2 == 0]
div_by_3 = [x for x in range(1, 31) if x % 3 == 0]
first_letters = [w[0].upper() for w in words]

EXERCISE 9:
for guess in guesses:
    attempt += 1
    if guess == secret:
        found = True
        break

EXERCISE 10:
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 11:
for i in range(1, 31):
    if i % 15 == 0:
        fizzbuzz_result.append("FizzBuzz")
    elif i % 3 == 0:
        fizzbuzz_result.append("Fizz")
    elif i % 5 == 0:
        fizzbuzz_result.append("Buzz")
    else:
        fizzbuzz_result.append(i)

EXERCISE 12:
cubes = {x: x**3 for x in range(1, 6)}
word_lengths = {w: len(w) for w in words}
even_squares = {x: x**2 for x in numbers if x % 2 == 0}

EXERCISE 13:
# Triangle
for i in range(1, 6):
    print("*" * i)

# Inverted
for i in range(5, 0, -1):
    print("*" * i)

EXERCISE 14:
for i in range(1, 6):
    for j in range(1, i + 1):
        print(j, end="")
    print()

EXERCISE 15:
def validate_password(password):
    failures = []
    if len(password) < 8:
        failures.append("too short")
    if not any(c.isupper() for c in password):
        failures.append("no uppercase")
    if not any(c.islower() for c in password):
        failures.append("no lowercase")
    if not any(c.isdigit() for c in password):
        failures.append("no digit")
    if not any(c in "!@#$%^&*" for c in password):
        failures.append("no special")
    return (len(failures) == 0, failures)
"""

print("\nšŸŽ‰ Great job! Move on to 04_data_structures when ready!")
Exercises - Python Tutorial | DeepML