Exercises: Python Basics
Practice variables, types, operators, strings, and collections with beginner Python exercises.
Related chapter: Python Basics
Exercise 1: Temperature Converter
Write a program that converts Celsius to Fahrenheit.
Input: 25
Output: 25°C = 77.0°F
Formula: F = C × 9/5 + 32
Hint
Use float(input()) and an f-string with :.1f for one decimal place.
Exercise 2: String Analyzer
Write a function analyze(text) that returns a dict with:
length— number of characterswords— number of wordsuppercase— count of uppercase letters
analyze("Hello World!")
# {'length': 12, 'words': 2, 'uppercase': 2}
Exercise 3: Even or Odd
Write a program that reads an integer and prints whether it’s even or odd, without using %.
Hint
Use n // 2 * 2 == n or bitwise n & 1 == 0.
Exercise 4: Shopping Total
Given a list of prices, calculate the total, average, and most expensive item:
prices = [12.99, 5.50, 24.00, 8.75, 3.25]
# Total: 54.49, Average: 10.90, Max: 24.00
Exercise 5: Word Counter
Ask the user for a sentence and print the count of each word (case-insensitive):
Input: "The cat and the dog"
Output: the: 2, cat: 1, and: 1, dog: 1
Hint
Use .lower().split() and a dictionary to count occurrences.
Exercise 6: FizzBuzz
Print numbers 1 to 30, but:
- “Fizz” for multiples of 3
- “Buzz” for multiples of 5
- “FizzBuzz” for multiples of both
Challenge: Password Validator
Write is_valid_password(password) that returns True if the password:
- Is at least 8 characters long
- Contains at least one uppercase letter
- Contains at least one digit
- Contains at least one special character (
!@#$%^&*)
Test with: "weak", "Strong1!", "NoSpecial1", "alllowercase!"
Solution (Exercise 1)
celsius = float(input("Enter °C: "))
fahrenheit = celsius * 9 / 5 + 32
print(f"{celsius}°C = {fahrenheit:.1f}°F")
Solution (Exercise 5)
sentence = input("Enter a sentence: ")
counts = {}
for word in sentence.lower().split():
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(f"{word}: {count}")
Exercise 7: List Statistics
Write stats(numbers) returning min, max, mean, and median for a non-empty list of numbers.
stats([3, 1, 4, 1, 5, 9, 2, 6])
# {'min': 1, 'max': 9, 'mean': 3.875, 'median': 3.5}
Exercise 8: Reverse Words
Write reverse_words(sentence) that reverses the order of words but not characters within each word.
reverse_words("Python is awesome")
# "awesome is Python"
Next: Control Flow Exercises