Python practice

A free place to write and run Python in your browser. Use the playground for anything you like, or work through the 50 exercises below. Each one checks your answer and tells you which tests pass.

Playground

Write any Python and press Run. Press Ctrl+Enter (or Cmd+Enter) to run from the keyboard. Press Escape and then Tab to leave the code box.

Input for input()

Exercises by week

Week 1: Meet Python: your first programs0 of 5 done
  1. 1. Say hello

    Easy

    Print exactly this line: Hello, Python!

    Hint

    Use print() with the text inside quotes. Capital letters and the punctuation must match.

    Show a solution
    print("Hello, Python!")

    There are many correct answers. If yours passes the checks, it is correct.

  2. 2. Area of a room

    Easy

    Create a variable length that holds 12, a variable width that holds 5, and a variable area that holds length times width.

    Hint

    area = length * width

    Show a solution
    length = 12
    width = 5
    area = length * width

    There are many correct answers. If yours passes the checks, it is correct.

  3. 3. Celsius to Fahrenheit

    Medium

    The variable celsius is 37. Create a variable fahrenheit using the formula celsius * 9 / 5 + 32.

    Hint

    Write the formula exactly as given. / gives a decimal answer, which is what you want here.

    Show a solution
    celsius = 37
    fahrenheit = celsius * 9 / 5 + 32

    There are many correct answers. If yours passes the checks, it is correct.

  4. 4. Greet by name

    Medium

    Ask for a name with input() and print Hello, <name>! using the name that was typed. For the name Asha the output is: Hello, Asha!

    Input for input()
    Hint

    print("Hello, " + name + "!") joins the pieces. You can also give print several values, but then spaces appear between them, so check the exact output.

    Show a solution
    name = input()
    print("Hello, " + name + "!")

    There are many correct answers. If yours passes the checks, it is correct.

  5. 5. Seconds to clock

    Challenge

    The variable total_seconds is 3725. Create three variables: hours, minutes and seconds so that they show the same time as hours, minutes and seconds (here 1, 2 and 5). Use // and % only.

    Hint

    hours = total_seconds // 3600. The leftover after that is total_seconds % 3600; split that leftover by 60 for minutes, and the remainder is seconds.

    Show a solution
    total_seconds = 3725
    hours = total_seconds // 3600
    left = total_seconds % 3600
    minutes = left // 60
    seconds = left % 60

    There are many correct answers. If yours passes the checks, it is correct.

Week 2: Working with text and numbers0 of 5 done
  1. 1. First and last letter

    Easy

    The variable word is "Python". Create first holding its first character and last holding its last character.

    Hint

    Index 0 is the first character; index -1 is the last.

    Show a solution
    word = "Python"
    first = word[0]
    last = word[-1]

    There are many correct answers. If yours passes the checks, it is correct.

  2. 2. Tidy an email

    Easy

    The variable raw is " [email protected] ". Create clean: the same text with the spaces removed from both ends and everything in lower case.

    Hint

    Chain strip() and lower().

    Show a solution
    raw = "  [email protected] "
    clean = raw.strip().lower()

    There are many correct answers. If yours passes the checks, it is correct.

  3. 3. Receipt line

    Medium

    Given item = "Notebook", qty = 3 and price = 45.5, print exactly: Notebook x3 = Rs 136.50 (the total with two decimal places).

    Hint

    Use an f-string: f"{item} x{qty} = Rs {qty * price:.2f}"

    Show a solution
    item = "Notebook"
    qty = 3
    price = 45.5
    print(f"{item} x{qty} = Rs {qty * price:.2f}")

    There are many correct answers. If yours passes the checks, it is correct.

  4. 4. Is it a palindrome?

    Medium

    Write a function is_palindrome(text) that returns True when the text reads the same forwards and backwards, ignoring upper or lower case. For example "Level" is a palindrome. (A function is covered in week 7; here you can copy the shape: def is_palindrome(text): then an indented return line.)

    Hint

    Lower-case the text first, then compare it with its reverse, text[::-1].

    Show a solution
    def is_palindrome(text):
        t = text.lower()
        return t == t[::-1]

    There are many correct answers. If yours passes the checks, it is correct.

  5. 5. Count the vowels

    Challenge

    Write a function count_vowels(text) that returns how many of the letters a, e, i, o, u appear in the text, in any case.

    Hint

    Lower-case the text and use a loop-free idea: add up 1 for each character that is in the string "aeiou". sum(1 for ch in text if ...) works, or a for loop from week 4.

    Show a solution
    def count_vowels(text):
        return sum(1 for ch in text.lower() if ch in "aeiou")

    There are many correct answers. If yours passes the checks, it is correct.

Week 3: Making decisions0 of 5 done
  1. 1. Adult or minor

    Easy

    Read a whole number from input(). Print Adult if it is 18 or more, otherwise print Minor.

    Input for input()
    Hint

    Compare with >= 18 inside an if, and use else for the other case.

    Show a solution
    age = int(input())
    if age >= 18:
        print("Adult")
    else:
        print("Minor")

    There are many correct answers. If yours passes the checks, it is correct.

  2. 2. Even or odd

    Easy

    Write a function parity(n) that returns the text "even" or "odd".

    Hint

    A number is even when n % 2 == 0.

    Show a solution
    def parity(n):
        if n % 2 == 0:
            return "even"
        return "odd"

    There are many correct answers. If yours passes the checks, it is correct.

  3. 3. Grade from marks

    Medium

    Write a function grade(marks): 90 or more gives "A", 75 to 89 gives "B", 60 to 74 gives "C", anything lower gives "D".

    Hint

    Use if, then elif for each lower band, then else. Check the highest band first.

    Show a solution
    def grade(marks):
        if marks >= 90:
            return "A"
        elif marks >= 75:
            return "B"
        elif marks >= 60:
            return "C"
        else:
            return "D"

    There are many correct answers. If yours passes the checks, it is correct.

  4. 4. Leap year

    Medium

    Write is_leap(year). A year is a leap year if it divides by 4, except years that divide by 100 are not, unless they also divide by 400. So 2024 and 2000 are leap years; 1900 and 2023 are not.

    Hint

    One line is enough: (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

    Show a solution
    def is_leap(year):
        return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

    There are many correct answers. If yours passes the checks, it is correct.

  5. 5. FizzBuzz for one number

    Challenge

    Write fizzbuzz(n). Return "FizzBuzz" if n divides by both 3 and 5, "Fizz" if only by 3, "Buzz" if only by 5, otherwise the number turned into text, such as "7".

    Hint

    Test the 'both' case first. If you test 3 first, 15 will wrongly give Fizz.

    Show a solution
    def fizzbuzz(n):
        if n % 15 == 0:
            return "FizzBuzz"
        if n % 3 == 0:
            return "Fizz"
        if n % 5 == 0:
            return "Buzz"
        return str(n)

    There are many correct answers. If yours passes the checks, it is correct.

Week 4: Repeating work with loops0 of 5 done
  1. 1. Countdown

    Easy

    Print the numbers from 5 down to 1, each on its own line, then print Liftoff!

    Hint

    range(5, 0, -1) counts down: 5, 4, 3, 2, 1.

    Show a solution
    for n in range(5, 0, -1):
        print(n)
    print("Liftoff!")

    There are many correct answers. If yours passes the checks, it is correct.

  2. 2. Sum up to n

    Easy

    Write sum_to(n) that returns 1 + 2 + ... + n. sum_to(4) is 10.

    Hint

    Start total = 0, loop over range(1, n + 1), add each number, then return total.

    Show a solution
    def sum_to(n):
        total = 0
        for i in range(1, n + 1):
            total += i
        return total

    There are many correct answers. If yours passes the checks, it is correct.

  3. 3. Times table

    Medium

    Read a number from input and print its table from 1 to 5, one line each, like 3 x 1 = 3.

    Input for input()
    Hint

    print(f"{n} x {i} = {n * i}") inside a for loop over range(1, 6).

    Show a solution
    n = int(input())
    for i in range(1, 6):
        print(f"{n} x {i} = {n * i}")

    There are many correct answers. If yours passes the checks, it is correct.

  4. 4. Prime check

    Medium

    Write is_prime(n). A prime is a whole number greater than 1 that only divides by 1 and itself.

    Hint

    Return False if n < 2. Then try every number d from 2 up to n - 1; if n % d == 0 return False. If no d works, return True.

    Show a solution
    def is_prime(n):
        if n < 2:
            return False
        for d in range(2, n):
            if n % d == 0:
                return False
        return True

    There are many correct answers. If yours passes the checks, it is correct.

  5. 5. Digits of a number

    Challenge

    Write digit_sum(n) that returns the sum of the digits of a positive whole number, using a while loop and // and % (no turning the number into text). digit_sum(472) is 13.

    Hint

    n % 10 is the last digit and n // 10 removes it. Repeat while n > 0.

    Show a solution
    def digit_sum(n):
        total = 0
        while n > 0:
            total += n % 10
            n = n // 10
        return total

    There are many correct answers. If yours passes the checks, it is correct.

Week 5: Lists and tuples0 of 5 done
  1. 1. Average mark

    Easy

    Write average(numbers) that returns the sum of a list divided by its length.

    Hint

    sum(numbers) / len(numbers)

    Show a solution
    def average(numbers):
        return sum(numbers) / len(numbers)

    There are many correct answers. If yours passes the checks, it is correct.

  2. 2. Second largest

    Medium

    Write second_largest(numbers) that returns the second largest different value in a list. second_largest([4, 9, 9, 7]) is 7. You may assume there are at least two different values.

    Hint

    Make the values unique with set(numbers), sort them from largest, and take index 1.

    Show a solution
    def second_largest(numbers):
        unique = sorted(set(numbers), reverse=True)
        return unique[1]

    There are many correct answers. If yours passes the checks, it is correct.

  3. 3. Keep the evens

    Easy

    Write evens(numbers) that returns a new list with only the even numbers, in the same order.

    Hint

    [n for n in numbers if n % 2 == 0]

    Show a solution
    def evens(numbers):
        return [n for n in numbers if n % 2 == 0]

    There are many correct answers. If yours passes the checks, it is correct.

  4. 4. Reverse without reverse()

    Medium

    Write backwards(items) that returns a new list with the items in reverse order. Do not change the original list and do not use reverse() or [::-1].

    Hint

    Start with an empty list and insert each item at position 0, or loop over range(len(items) - 1, -1, -1).

    Show a solution
    def backwards(items):
        result = []
        for item in items:
            result.insert(0, item)
        return result

    There are many correct answers. If yours passes the checks, it is correct.

  5. 5. Merge two sorted lists

    Challenge

    Write merge(a, b) that takes two lists that are already sorted from smallest to largest and returns one sorted list containing everything. Try to do it with two positions walking along the lists instead of just sorting the joined list.

    Hint

    Keep i for list a and j for list b. Compare a[i] and b[j], append the smaller one and move that position along. When one list runs out, add what is left of the other.

    Show a solution
    def merge(a, b):
        result = []
        i = j = 0
        while i < len(a) and j < len(b):
            if a[i] <= b[j]:
                result.append(a[i])
                i += 1
            else:
                result.append(b[j])
                j += 1
        result.extend(a[i:])
        result.extend(b[j:])
        return result

    There are many correct answers. If yours passes the checks, it is correct.

Week 6: Dictionaries and sets0 of 5 done
  1. 1. Count words

    Easy

    Write word_count(text) that returns a dictionary of how many times each word appears. Split the text on spaces and treat words as they are. word_count("a b a") is {"a": 2, "b": 1}.

    Hint

    Make counts = {}. For each word, counts[word] = counts.get(word, 0) + 1.

    Show a solution
    def word_count(text):
        counts = {}
        for word in text.split():
            counts[word] = counts.get(word, 0) + 1
        return counts

    There are many correct answers. If yours passes the checks, it is correct.

  2. 2. Remove duplicates, keep order

    Medium

    Write unique(items) that returns a list with the duplicates removed but the first occurrence of each item kept in its original order. unique([3, 1, 3, 2, 1]) is [3, 1, 2].

    Hint

    Keep a set called seen and a result list. Add an item only if it is not in seen yet.

    Show a solution
    def unique(items):
        seen = set()
        result = []
        for item in items:
            if item not in seen:
                seen.add(item)
                result.append(item)
        return result

    There are many correct answers. If yours passes the checks, it is correct.

  3. 3. Swap keys and values

    Medium

    Write invert(d) that returns a new dictionary with keys and values swapped. You may assume all values are different. invert({"a": 1, "b": 2}) is {1: "a", 2: "b"}.

    Hint

    Loop over d.items() and set result[value] = key.

    Show a solution
    def invert(d):
        return {value: key for key, value in d.items()}

    There are many correct answers. If yours passes the checks, it is correct.

  4. 4. Common interests

    Easy

    Write common(a, b) that returns a sorted list of the items that appear in both lists.

    Hint

    set(a) & set(b) gives the shared items. Wrap it in sorted(...).

    Show a solution
    def common(a, b):
        return sorted(set(a) & set(b))

    There are many correct answers. If yours passes the checks, it is correct.

  5. 5. Group the anagrams

    Challenge

    Write group_anagrams(words) that returns a list of groups. Words that use exactly the same letters belong together. Keep groups in the order their first word appears and words in input order. group_anagrams(["eat", "tea", "tan", "ate", "nat"]) is [["eat", "tea", "ate"], ["tan", "nat"]].

    Hint

    The sorted letters of a word are the same for every anagram: "".join(sorted(word)). Use that as a dictionary key whose value is a list of words.

    Show a solution
    def group_anagrams(words):
        groups = {}
        for word in words:
            key = "".join(sorted(word))
            groups.setdefault(key, []).append(word)
        return list(groups.values())

    There are many correct answers. If yours passes the checks, it is correct.

Week 7: Functions: reusable building blocks0 of 5 done
  1. 1. Square it

    Easy

    Write square(n) that returns n multiplied by itself.

    Hint

    return n * n

    Show a solution
    def square(n):
        return n * n

    There are many correct answers. If yours passes the checks, it is correct.

  2. 2. BMI calculator

    Medium

    Write bmi(weight_kg, height_m) that returns weight divided by height squared, rounded to one decimal place.

    Hint

    round(weight_kg / (height_m ** 2), 1)

    Show a solution
    def bmi(weight_kg, height_m):
        return round(weight_kg / (height_m ** 2), 1)

    There are many correct answers. If yours passes the checks, it is correct.

  3. 3. Power with a default

    Medium

    Write power(base, exponent=2). With one argument it squares the number. power(3) is 9 and power(2, 10) is 1024.

    Hint

    return base ** exponent

    Show a solution
    def power(base, exponent=2):
        return base ** exponent

    There are many correct answers. If yours passes the checks, it is correct.

  4. 4. Return two values

    Medium

    Write stats(numbers) that returns a pair: the smallest and the largest number. stats([3, 9, 1]) is (1, 9).

    Hint

    return min(numbers), max(numbers)

    Show a solution
    def stats(numbers):
        return min(numbers), max(numbers)

    There are many correct answers. If yours passes the checks, it is correct.

  5. 5. Fibonacci numbers

    Challenge

    Write fib(n) that returns the n-th Fibonacci number, where fib(0) is 0, fib(1) is 1 and each later number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8...

    Hint

    Keep two variables, a = 0 and b = 1, and repeat n times: a, b = b, a + b. Then return a.

    Show a solution
    def fib(n):
        a, b = 0, 1
        for _ in range(n):
            a, b = b, a + b
        return a

    There are many correct answers. If yours passes the checks, it is correct.

Week 8: Errors, files and JSON0 of 5 done
  1. 1. Safe number reader

    Easy

    Write to_int(text, default=0) that returns int(text), or the default if the text is not a whole number.

    Hint

    Put int(text) in a try block and return default from except ValueError.

    Show a solution
    def to_int(text, default=0):
        try:
            return int(text)
        except ValueError:
            return default

    There are many correct answers. If yours passes the checks, it is correct.

  2. 2. Divide safely

    Easy

    Write safe_divide(a, b) that returns a / b, or the text "cannot divide by zero" when b is zero.

    Hint

    Catch ZeroDivisionError, or check b == 0 first.

    Show a solution
    def safe_divide(a, b):
        try:
            return a / b
        except ZeroDivisionError:
            return "cannot divide by zero"

    There are many correct answers. If yours passes the checks, it is correct.

  3. 3. Count lines in a file

    Medium

    Write count_lines(filename) that returns how many lines the file has. The check will create a file for you.

    Hint

    Open the file with with, then len(f.readlines()) or count the lines in a for loop.

    Show a solution
    def count_lines(filename):
        with open(filename) as f:
            return len(f.readlines())

    There are many correct answers. If yours passes the checks, it is correct.

  4. 4. Save and load a dictionary

    Medium

    Write save_json(data, filename) that writes the dictionary to a file as JSON, and load_json(filename) that reads it back.

    Hint

    json.dump(data, f) inside open(filename, "w"), and json.load(f) inside open(filename).

    Show a solution
    import json
    
    def save_json(data, filename):
        with open(filename, "w") as f:
            json.dump(data, f)
    
    def load_json(filename):
        with open(filename) as f:
            return json.load(f)

    There are many correct answers. If yours passes the checks, it is correct.

  5. 5. Clean up messy numbers

    Challenge

    Write total_valid(items) that adds up the entries of a list that can be read as numbers (like "12" or "3.5") and silently skips the rest (like "n/a" or ""). total_valid(["12", "x", "3.5"]) is 15.5.

    Hint

    Loop over the items, try float(item), and skip with except ValueError.

    Show a solution
    def total_valid(items):
        total = 0
        for item in items:
            try:
                total += float(item)
            except ValueError:
                continue
        return total

    There are many correct answers. If yours passes the checks, it is correct.

Week 9: Modules and classes0 of 5 done
  1. 1. Circle area with math

    Easy

    Write circle_area(radius) using math.pi. Round the answer to 2 decimal places.

    Hint

    round(math.pi * radius ** 2, 2)

    Show a solution
    import math
    
    def circle_area(radius):
        return round(math.pi * radius ** 2, 2)

    There are many correct answers. If yours passes the checks, it is correct.

  2. 2. Days until

    Medium

    Write days_between(start, end) that takes two dates written as "YYYY-MM-DD" text and returns the number of days from start to end. days_between("2026-12-25", "2027-01-01") is 7.

    Hint

    date.fromisoformat(text) converts the text into a date. Subtract the dates and use .days.

    Show a solution
    from datetime import date
    
    def days_between(start, end):
        return (date.fromisoformat(end) - date.fromisoformat(start)).days

    There are many correct answers. If yours passes the checks, it is correct.

  3. 3. A Rectangle class

    Medium

    Write a class Rectangle with attributes width and height and two methods: area() and perimeter().

    Hint

    Set self.width = width and self.height = height inside __init__. Then add def area(self): return self.width * self.height.

    Show a solution
    class Rectangle:
        def __init__(self, width, height):
            self.width = width
            self.height = height
    
        def area(self):
            return self.width * self.height
    
        def perimeter(self):
            return 2 * (self.width + self.height)

    There are many correct answers. If yours passes the checks, it is correct.

  4. 4. A counter class

    Medium

    Write a class Counter with a count that starts at 0, a method add() that increases it by 1 and a method reset() that sets it back to 0.

    Hint

    Set self.count = 0 in __init__. add does self.count += 1.

    Show a solution
    class Counter:
        def __init__(self):
            self.count = 0
    
        def add(self):
            self.count += 1
    
        def reset(self):
            self.count = 0

    There are many correct answers. If yours passes the checks, it is correct.

  5. 5. Build a Stack

    Challenge

    Write a class Stack (last in, first out) with push(item), pop() that removes and returns the newest item, peek() that returns it without removing, is_empty(), and size(). pop() on an empty stack should raise IndexError.

    Hint

    Keep a list in self.items. push appends and pop uses the list's own pop(), which already raises IndexError when empty.

    Show a solution
    class Stack:
        def __init__(self):
            self.items = []
    
        def push(self, item):
            self.items.append(item)
    
        def pop(self):
            return self.items.pop()
    
        def peek(self):
            return self.items[-1]
    
        def is_empty(self):
            return len(self.items) == 0
    
        def size(self):
            return len(self.items)

    There are many correct answers. If yours passes the checks, it is correct.

Week 10: Put it together: a project and what comes next0 of 5 done
  1. 1. Letter grade from a list

    Easy

    Write letter(marks) that takes a list of marks and returns the letter for the average: 90 or more A, 75 or more B, 60 or more C, otherwise D.

    Hint

    Work out the average first, then reuse the if/elif idea from week 3.

    Show a solution
    def letter(marks):
        avg = sum(marks) / len(marks)
        if avg >= 90:
            return "A"
        if avg >= 75:
            return "B"
        if avg >= 60:
            return "C"
        return "D"

    There are many correct answers. If yours passes the checks, it is correct.

  2. 2. A tiny to-do list

    Medium

    Write a class Todo with add(task), done(task) which removes a finished task, and pending() which returns the list of tasks still to do in the order they were added. done() on a task that is not there should do nothing.

    Hint

    Keep self.tasks = [] in __init__. In done(), check if task in self.tasks before calling remove.

    Show a solution
    class Todo:
        def __init__(self):
            self.tasks = []
    
        def add(self, task):
            self.tasks.append(task)
    
        def done(self, task):
            if task in self.tasks:
                self.tasks.remove(task)
    
        def pending(self):
            return list(self.tasks)

    There are many correct answers. If yours passes the checks, it is correct.

  3. 3. Top words

    Medium

    Write top_words(text, n) that returns the n most common words as a list of (word, count) pairs, most common first. Compare in lower case and ignore punctuation by splitting only on spaces after removing the characters . , ! ? from the text. If two words have the same count, keep the one that appears first in the text first.

    Hint

    Remove punctuation with replace, lower() and split(). Counter(words).most_common(n) keeps first-seen order for equal counts.

    Show a solution
    from collections import Counter
    
    def top_words(text, n):
        for ch in ".,!?":
            text = text.replace(ch, "")
        words = text.lower().split()
        return Counter(words).most_common(n)

    There are many correct answers. If yours passes the checks, it is correct.

  4. 4. Password checker

    Medium

    Write password_problems(pw) that returns a list of problems: "too short" if under 8 characters, "no digit" if it has no digit and "no uppercase" if it has no capital letter, in that order. A good password returns an empty list.

    Hint

    Use len(pw), any(ch.isdigit() for ch in pw) and any(ch.isupper() for ch in pw).

    Show a solution
    def password_problems(pw):
        problems = []
        if len(pw) < 8:
            problems.append("too short")
        if not any(ch.isdigit() for ch in pw):
            problems.append("no digit")
        if not any(ch.isupper() for ch in pw):
            problems.append("no uppercase")
        return problems

    There are many correct answers. If yours passes the checks, it is correct.

  5. 5. Balanced brackets

    Challenge

    Write balanced(text) that returns True if every ( [ { in the text is closed by the matching ) ] } in the right order, ignoring all other characters. balanced("([]{})") is True and balanced("(]") is False.

    Hint

    Walk through the text with a list used as a stack. Push an opening bracket; for a closing bracket the top of the stack must be its partner, otherwise return False. At the end the stack must be empty.

    Show a solution
    def balanced(text):
        pairs = {")": "(", "]": "[", "}": "{"}
        stack = []
        for ch in text:
            if ch in "([{":
                stack.append(ch)
            elif ch in pairs:
                if not stack or stack.pop() != pairs[ch]:
                    return False
        return not stack

    There are many correct answers. If yours passes the checks, it is correct.