the full guide

Python exercises

Practice exercises are short problems that make you write the code yourself. Learning to program comes from writing and fixing code, and reading alone won't do it.

60 min Intermediate

What you need: The earlier topics of this module.

Definition

Practice exercises are short problems that make you write the code yourself. Learning to program comes from writing and fixing code, and reading alone won't do it.

In simple words

You can't learn to swim by reading about water. Try each of these before looking anything up.

Why it matters

Trying first, and being wrong, makes ideas stick far better than rereading. These cover each chapter of the module.

How it works

Basics

  1. Ask for a name and a birth year, and print the age.
  2. Print whether a number is even or odd.
  3. Print the multiplication table of any number.

Strings and lists

  1. Count the vowels in a sentence.
  2. Check whether a word is a palindrome.
  3. Remove duplicates from a list, keeping the order.
  4. Find the second-largest number in a list.

Dicts and functions

  1. Count how often each word appears in a text.
  2. Write a function that returns the mean, median and mode.
  3. Write a recursive function for factorial.

Files and classes

  1. Read a CSV of marks, and write the toppers to a new file.
  2. Build a BankAccount class that refuses overdrafts.
  3. Add a custom exception to it, plus three tests.

In code

Exercise 5 solved, to show the style. Press Run and edit, then try the others in the same box.

start_here.py
def is_palindrome(word):
    word = word.lower()
    return word == word[::-1]

for word in ["Nitin", "Python", "Malayalam"]:
    print(word, is_palindrome(word))

Output

Nitin True
Python False
Malayalam True

Common mistakes

  • Copying a solution before trying. You'll feel you understand it, and won't be able to write it.
  • Skipping the errors. Reading and fixing your errors is the lesson.

Check yourself

Question 1

1. What's the best way to learn from these?

Question 2

2. What does word[::-1] do?

Summary

  • Write code yourself, and don't just read.
  • Try before you look anything up.

Finished reading?