Python Exercises For All Levels – A Collection

If you are searching for Python Exercises to practice your programming skills, you have come to the right place. This ever-growing list of Python Exercises is a collection of beginner-friendly Python coding challenges that help you to become a better Python programmer. We will keep adding new challenges to this list regularly, so make sure to bookmark and check back for new content.

Python Exercises Top

Table of Contents

Requirements

There is not much that you need to participate in any of these challenges. The only thing you need is a free Replit account. This is the easiest way to directly start coding and working on our challenges.

We provide a Starter Repl and a Solution Repl to each exercise. We encourage you not to look at the Solution Repl until you are completely stuck. Use Google to help find a solution and hone your Google skills simultaneously. The best way to learn is to struggle!

How to fork a Repl

ℹ️ This article has a corresponding Replit repository that you can copy and play around with. Create a free Replit account and click on the Fork Repl button below. This is the best way to practice programming!

To fork a Repl, you just have to click on the Starter Repl button, make sure you are logged in to your Replit account, and click on the Fork Repl button to create a copy of the Starter Repl we provide. This allows you to start coding directly.

Python Excercise 1 – Crypto Coin Name Generator

Difficulty: Very Easy

In this exercise, we will build a Crypto Coin Name Generator. This covers a lot of Python’s basic functionality by using variables, input, and print.

Task

  1. Ask the user for his favorite toy as a kid using input and store it in a variable (If the toy has multiple words, just write it in PascalCase ex: ActionMan)
  2. Ask the user if the Crypto Coin should end with “Token”, “Coin”, or something else.
  3. Print the name of the new Crypto Coin to the console!
  4. Bonus: Make sure to print a newline character after asking the user a question so that the user has a clear input field!

Hints

You need to use the following Python functions to be able to solve this challenge:

  • print()
  • input()

Final Program

The final program should look like this:

Python Exercise 1 Final Program

Python Exercise 2 – BMI Calculator

Difficulty: Very Easy

In this exercise, we will create a BMI calculator! This will help us to better understand different data types and help us to learn how to use them in a program. The formula to calculate the BMI is:

Python Exercise 2

Task

  • Write a program that calculates a user’s BMI using the user’s weight and height.
  • BMI is calculated by dividing the person’s weight in kg by the square of the person’s height in meters.
  • Round the result to a whole number.

Hints

  1. Check the data types of your variables/inputs.
  2. If you can, use the exponent operator in your program.
  3. Convert your result to a whole number.

Final Program

If you make the following input:

height = 1.85
weight = 75

You should receive this output:

22

Based on the calculation using the BMI formula: 75 % (1.85 x 1.85)

Python Exercise 2

This result is already rounded. If you don’t round, you will end up with a long floating point number!

Python Exercise 3 – Time Left to Live

Difficulty: Very Easy

We have recently come across this fun app by Bryan Braun, which lets you calculate your life in weeks, months, and years. We thought this would be a funny Python exercise. We will do something similar, but with a little twist!

Task

  • Create a program that takes the user’s current age as input and calculates how many days, weeks, and months they have left to live if they would get 99 years old.
  • For this exercise, we assume that a year has 365 days, 52 weeks, and 12 months. We don’t take leap years into account!
  • Print the final result to the console using an f-String!

Hints

  • For this program, you need to convert the user input to an integer.
  • You can use the following built-in Python functions to solve this challenge:

Final Program

If you make the following input:

36Code language: plaintext (plaintext)
Python Exercise 3

You should get the following output (adjust your f-String to match the output exactly!):

Python Exercise 3 Solution

Best of luck!

Python Exercise 4 – The Tip Calculator

Difficulty: Easy

This is going to be a fun exercise where we are going to practice our understanding of Python’s mathematical operations! We will also be working with f-strings again. Your task in this exercise is to build a Tip Calculator. Imagine you are having dinner with a group of friends, and you want to split the bill, including the tip for the waiter, equally, among your friends – this is exactly what we are going to build!

Task

  1. Print a greeting to the screen, welcoming our user to the Tip Calculator.
  2. Ask the user how much the total bill is and store the value in a variable.
  3. Ask the user how much percent tip they want to give the waiter and store the value in a variable.
  4. Ask the user how many people they want to split the bill between and store the value in a variable.
  5. Calculate how much each of your friends has to pay if the bill, including tip, is equally spread among them.
  6. Round the result to two positions after the comma and print it to the console
  • BONUS: When you input the following amounts:
    • Total bill: 150
    • Tip percentage: 12
    • Split between people: 5

The total amount paid by each person should be $33.60, not $33.6. You have to do some Googling to find out how to do that!

Hints

This challenge can be a bit tricky, especially the bonus task, but be confident in yourself – you got this! Here are some tips:

  • If the bill is 150$ split between 5 people with a 12% tip, you can use this formula to calculate the final amount each person has to pay (feel free to use any other formula to get to the result!):
    • 150/5 * 1.12
  • You can use the following built-in Python functions to help solve this challenge:
    • round()
    • int()
    • float()
    • f-strings

Final Program

If you enter the following values:

  • Total bill: 180
  • Tip percentage: 15
  • Split between people: 4

The result should be:

Python Exercise 4 Solution

I’ll create 3 new Python exercises following a similar style and difficulty level as the examples provided. I’ll include tasks, hints, and solutions.

Python Exercise 5 – Password Strength Checker

Difficulty: Easy

Create a program that checks the strength of a password and provides feedback to the user.

Task

  • Ask the user to input a password
  • Check the password against the following criteria:
  • At least 8 characters long
  • Contains at least one uppercase letter
  • Contains at least one lowercase letter
  • Contains at least one number
  • Contains at least one special character (!@#$%^&*()_+-=)
  • Print out which criteria the password meets and doesn’t meet
  • Give the password a strength rating: Weak, Medium, or Strong

Hints

  • You can use string methods to check for different types of characters
  • Consider using boolean variables to track which criteria are met
  • The any() function can be helpful when checking for character types

Solution

def check_password_strength(password):
    criteria = {
        'length': len(password) >= 8,
        'uppercase': any(c.isupper() for c in password),
        'lowercase': any(c.islower() for c in password),
        'number': any(c.isdigit() for c in password),
        'special': any(c in '!@#$%^&*()_+-=' for c in password)
    }

    print("\nPassword Check Results:")
    for criterion, is_met in criteria.items():
        print(f"{criterion.title()}: {'✓' if is_met else '✗'}")

    # Calculate strength
    strength = sum(criteria.values())
    if strength <= 2:
        return "Weak"
    elif strength <= 4:
        return "Medium"
    else:
        return "Strong"

password = input("Enter a password to check: ")
strength = check_password_strength(password)
print(f"\nPassword Strength: {strength}")Code language: PHP (php)

Python Exercise 6 – Word Counter

Difficulty: Easy

Create a program that analyzes text and provides statistics about the words used.

Task

  • Ask the user to input a sentence or paragraph
  • Calculate and display:
  • Total number of words
  • Number of unique words
  • Most common word and how many times it appears
  • Average word length
  • Ignore case (treat “Hello” and “hello” as the same word)
  • Ignore punctuation

Hints

  • Split the text into words using the split() method
  • Use a dictionary to count word frequencies
  • The string module has helpful constants for punctuation
  • Consider using list comprehensions for cleaning the text

Solution

import string
from collections import Counter

def analyze_text(text):
    # Clean the text
    text = text.lower()
    for punct in string.punctuation:
        text = text.replace(punct, '')

    # Split into words
    words = text.split()

    # Count frequencies
    word_counts = Counter(words)

    # Calculate statistics
    total_words = len(words)
    unique_words = len(word_counts)
    most_common = word_counts.most_common(1)[0] if words else ('', 0)
    avg_length = sum(len(word) for word in words) / total_words if words else 0

    # Print results
    print(f"\nText Analysis:")
    print(f"Total words: {total_words}")
    print(f"Unique words: {unique_words}")
    print(f"Most common word: '{most_common[0]}' ({most_common[1]} times)")
    print(f"Average word length: {avg_length:.1f} characters")

text = input("Enter some text to analyze: ")
analyze_text(text)Code language: PHP (php)

Python Exercise 7 – Temperature Converter

Difficulty: Very Easy

Create a program that converts temperatures between Celsius, Fahrenheit, and Kelvin.

Task

  • Ask the user for:
  • Input temperature value
  • Input temperature scale (C, F, or K)
  • Desired output scale (C, F, or K)
  • Convert the temperature to the desired scale
  • Round the result to 1 decimal place
  • Print the result with the appropriate units
  • Handle invalid inputs gracefully

Hints

  • Use functions for each type of conversion
  • Remember the conversion formulas:
  • C to F: (C × 9/5) + 32
  • C to K: C + 273.15
  • F to C: (F – 32) × 5/9
  • Use a dictionary to store conversion functions
  • Handle case-insensitive input

Solution

def celsius_to_fahrenheit(c):
    return (c * 9/5) + 32

def celsius_to_kelvin(c):
    return c + 273.15

def fahrenheit_to_celsius(f):
    return (f - 32) * 5/9

def kelvin_to_celsius(k):
    return k - 273.15

def convert_temperature():
    # Get input from user
    try:
        temp = float(input("Enter temperature value: "))
        from_scale = input("Enter current scale (C/F/K): ").upper()
        to_scale = input("Enter desired scale (C/F/K): ").upper()

        # First convert to Celsius as intermediate step
        if from_scale == 'C':
            celsius = temp
        elif from_scale == 'F':
            celsius = fahrenheit_to_celsius(temp)
        elif from_scale == 'K':
            celsius = kelvin_to_celsius(temp)
        else:
            print("Invalid input scale!")
            return

        # Convert from Celsius to desired scale
        if to_scale == 'C':
            result = celsius
            unit = '°C'
        elif to_scale == 'F':
            result = celsius_to_fahrenheit(celsius)
            unit = '°F'
        elif to_scale == 'K':
            result = celsius_to_kelvin(celsius)
            unit = 'K'
        else:
            print("Invalid output scale!")
            return

        print(f"\n{temp}°{from_scale} = {result:.1f}{unit}")

    except ValueError:
        print("Please enter a valid number for temperature!")

convert_temperature()Code language: PHP (php)

These exercises cover various Python concepts including:

  • String manipulation
  • Data structures (dictionaries, lists)
  • Functions and error handling
  • User input and output formatting
  • Mathematical operations
  • Type conversion
  • Control flow

Each exercise builds on basic Python concepts while introducing new functions and methods, helping learners develop their programming skills incrementally.

Where to go from here?

After you have finished all of our exercises, make sure to bookmark this site since we keep adding new Python exercises weekly. If you want to learn even more about Python, we highly recommend checking out our Python section, where we teach you the Python programming language from the ground up in a beginner-friendly way!

🐍 Learn Python Programming
🔨 Python Basics
👉 Python Syntax
👉 Python Variables
👉 Python print()
👉 Python input()
👉 Python Constants
👉 Python Comments
⚙️ Python Specifics
👉 Filter Lists in Python
👉 Replacing List Items in Python
👉 Create a GUI in Python
👉 Find out the Length of a String in Python
👉 Enum in Python
👉 Python Inline If/Else One-Line Statements
👉 Python xrange()
👉 Python List Slicing
🏋️ Python Exercises
👉 Python Exercise Collection

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap