Skip to content

Solutions – Python Basics Exercises

These reference solutions demonstrate one approach to each practice task from Lesson 02 – Python Basics. Use them to compare with your own attempts and understand the reasoning behind each step.


Exercise 1: FizzBuzz

for i in range(1, 21):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)
This loop iterates from 1 through 20. Checking divisibility by 3 and 5 first ensures numbers like 15 output "FizzBuzz" rather than just "Fizz" or "Buzz".

Exercise 2: Reverse a String

word = input("Enter a word: ")
print(word[::-1])
word[::-1] uses Python slicing to step backward through the string, producing the reversed order.

Exercise 3: Prime Checker

n = int(input("Enter a number: "))
if n < 2:
    print(f"{n} is not prime")
else:
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            print(f"{n} is not prime")
            break
    else:
        print(f"{n} is prime")
The loop tries divisors up to the square root of n. If none divide evenly, the number is prime. The else block on the for loop runs only when no break occurs.

Exercise 4: Word Counter

sentence = input("Enter a sentence: ")
words = sentence.split()
print(len(words))
split() separates the sentence on whitespace, producing a list of words. Taking len() of that list gives the count.

Exercise 5: Temperature Converter

celsius = float(input("Temperature in C: "))
fahrenheit = celsius * 9 / 5 + 32
print(fahrenheit)
Multiplying by 9/5 then adding 32 converts the Celsius value to Fahrenheit.