Python Exercises
Fill in the blanks to check your knowledge. Each exercise belongs to a lesson.
Python Introduction
Exercise
Print the text Hi.
("Hi")Getting Started
Exercise
Which command runs a file called app.py?
app.pyPython Syntax
Exercise
Finish the line that starts an if block.
if 5 > 2 print("yes")
Output with print()
Exercise
Change the separator to a dash.
print("x", "y", ="-")
Comments
Exercise
Which symbol starts a comment?
this is ignoredVariables and Types
Exercise
Store the number 10 in x.
x 10
Variable Names
Exercise
Which style do Python variables normally use?
firstname = "Ada"
Assigning Many Values
Exercise
Give three variables the same value.
a = b = c = Global and Local Variables
Exercise
Allow a function to change the global count.
def add(): count count += 1
Data Types
Exercise
Find the type of a value.
print((42))
Numbers
Exercise
Divide and drop the decimal part.
print(7 2)
Casting
Exercise
Turn the text into a whole number.
total = ("5") + 1
Booleans
Exercise
Which value means true?
is_ok = Operators
Exercise
Check that the letter is inside the word.
print("a" "cat")
None
Exercise
Check for None correctly.
if value None: print("empty")
Numbers: int, float and complex
Exercise
Floor division.
print(7 2)
Booleans and None
Exercise
Check for None.
x None
Input and Output
Exercise
Read user text.
name = ("Name: ")
Type Conversion
Exercise
Convert to text.
(5)Operators: Comparison, Logical, Membership
Exercise
Chained check.
print(1 x < 10)
Comments and Docstrings
Exercise
Start a comment.
noteStrings
Exercise
Make the text uppercase.
print("hello".())
Slicing Strings and Lists
Exercise
Get the first three characters.
print("Python"[:3])
String Methods
Exercise
Remove the spaces at both ends.
print(" hi ".())
String Formatting
Exercise
Start an f-string.
name = "Ada" print("Hello {name}")
Escape Characters
Exercise
Which escape makes a new line?
print("ab")
String Slicing and Indexing
Exercise
Reverse a string.
s[]
More String Methods
Exercise
Join with a dash.
"-".(["a","b"])
f-strings in Depth
Exercise
Two decimals.
f"{pi:}"
Checking and Cleaning Strings
Exercise
Digits only.
"12".()
Lists
Exercise
Add an item to the end.
fruits = ["apple"] fruits.("mango")
List Methods
Exercise
Add an item to the end.
items.("x")
List Comprehension
Exercise
Complete the comprehension.
[n * 2 n in [1, 2, 3]]
Sorting Lists
Exercise
Sort without changing the original.
new = (old)
Copying Lists
Exercise
Make a real copy.
b = a.()
Tuples
Exercise
Create a tuple with one item.
t = (5)
Sets
Exercise
Find the values in both sets.
print(a b)
Dictionaries
Exercise
Read the age.
user = {"age": 21} print(user[])
Dictionary Methods
Exercise
Loop over keys and values together.
for k, v in user.(): pass
Nested Collections
Exercise
Read the first score of the first student.
print(students[0]["scores"][])
Dictionary and Set Comprehensions
Exercise
Build a dictionary comprehension.
{w: len(w) w in words}
List Methods
Exercise
Add one item.
a.(4)
List Comprehensions
Exercise
Squares.
[n 2 for n in a]
Tuples and Unpacking
Exercise
Gather the rest.
a, rest = t
Dictionary Methods
Exercise
Safe lookup.
d.("x", 0)
Sets and Set Operations
Exercise
Common items.
a b
collections: Counter, defaultdict, deque
Exercise
Count items.
("hello")Sorting with key and Sorted
Exercise
Sort rule argument.
sorted(x, =len)
Conditions
Exercise
Add the missing keyword.
x = 5 x > 3: print("big")
The match Statement
Exercise
Write the default case.
match x: case 1: pass case : pass
Loops
Exercise
Loop over the numbers 0 to 4.
for i in (5): print(i)
While Loops
Exercise
Subtract one each time.
while n > 0: n 1
break, continue and else
Exercise
Skip to the next round.
for n in range(5):
if n == 2:
The range() Function
Exercise
Count from 10 down to 1.
list(range(10, 0, ))
enumerate() and zip()
Exercise
Get position and item together.
for i, x in (items): pass
if, elif and else
Exercise
Else if keyword.
n > 5:while Loops, break and continue
Exercise
Skip an iteration.
for Loops and range
Exercise
Index and value.
for i, v in (items):
match Statement
Exercise
Default case.
case :
Functions
Exercise
Define a function.
add(a, b):
return a + bFunction Arguments
Exercise
Give the parameter a default of 1.
def buy(item, qty1): pass
Return Values
Exercise
Send a value back from the function.
def add(a, b): a + b
Lambda Functions
Exercise
Create a lambda.
square = x: x * x
Scope and the LEGB Rule
Exercise
Change a variable of the enclosing function.
def add(): n n += 1
Recursion
Exercise
Name the part that stops the calls.
if n <= 1: return 1 # the case
Decorators
Exercise
Apply the decorator.
shout
def hi():
return "hi"Iterators
Exercise
Get the next item of an iterator.
print((it))
Generators
Exercise
Produce a value from a generator.
def numbers(): 1
*args and **kwargs
Exercise
Collect keyword args.
def f(kw): pass
lambda, map, filter
Exercise
Anonymous function.
x: x + 1Scope: local, global, nonlocal
Exercise
Rebind a global.
countDecorators Basics
Exercise
Apply a decorator.
shoutGenerators and yield
Exercise
Produce a value.
iModules and import
Exercise
Import one name from a module.
math import sqrtPackages and pip
Exercise
Which command installs a package?
pip requests
The math Module
Exercise
Round up to the next whole number.
math.(4.1)
The random Module
Exercise
Pick one item from a list.
random.(["a", "b"])
Dates and Times
Exercise
Add 7 days to a date.
d + (days=7)
JSON
Exercise
Turn JSON text into a Python value.
data = json.(text)
Regular Expressions
Exercise
Find all matches.
re.(r"\d+", text)
The collections Module
Exercise
Count the items.
from collections import Standard Library Tour
Exercise
Square root.
math.(16)
pathlib for File Paths
Exercise
Join paths.
Path("a") "b"
User Input
Exercise
Read a line typed by the user.
name = ("Name: ")
Reading Files
Exercise
Make sure the file closes by itself.
open("a.txt") as f:
data = f.read()Writing and Appending
Exercise
Add text to the end of a file.
open("log.txt", "")
Files and Folders with os
Exercise
Delete a file.
os.("old.txt")
Reading and Writing Files
Exercise
Append mode.
open(p, "")
JSON and CSV
Exercise
Text to object.
json.(s)
Classes and Objects
Exercise
Start a class definition.
Dog:
passThe __init__ Method
Exercise
Name the setup method.
class A: def (self): pass
Methods and self
Exercise
The first parameter of a method is...
def show(): pass
Inheritance
Exercise
Call the parent version.
().speak()Polymorphism
Exercise
Call the shared method on each shape.
for s in shapes: print(s.())
Class and Instance Attributes
Exercise
Mark a method that receives the class.
classmethod
def make(cls):
passSpecial (Dunder) Methods
Exercise
Which method gives the text shown by print?
def (self): return "text"
Dataclasses
Exercise
Import the decorator.
from dataclasses import Dataclasses
Exercise
Dataclass decorator.
@ class A: pass
Special Methods
Exercise
Text of an object.
def (self):
Errors and try/except
Exercise
Catch the error.
try: int("x") ValueError: print("bad")
Raising Errors
Exercise
Signal an error.
ValueError("bad value")try, except, else and finally
Exercise
Which block always runs?
try: pass except Exception: pass : print("always")
Testing with assert
Exercise
Check that a condition holds.
add(2, 2) == 4raise and Custom Exceptions
Exercise
Throw an error.
ValueError("x")Type Hints
Premium exercise. See plans
Virtual Environments
Premium exercise. See plans
Style Guide (PEP 8)
Premium exercise. See plans
Decorators
Premium exercise. See plans
Decorators With Arguments
Premium exercise. See plans
Generators and yield
Premium exercise. See plans
Generator Pipelines and yield from
Premium exercise. See plans
The Iterator Protocol
Premium exercise. See plans
Context Managers
Premium exercise. See plans
Dataclasses
Premium exercise. See plans
Advanced Typing
Premium exercise. See plans
functools: cache, partial and reduce
Premium exercise. See plans
itertools
Premium exercise. See plans
Properties and Descriptors
Premium exercise. See plans
Special Methods
Premium exercise. See plans
Abstract Classes and Enums
Premium exercise. See plans
Metaclasses and Class Hooks
Premium exercise. See plans
__slots__ and Memory
Premium exercise. See plans
asyncio Basics
Premium exercise. See plans
Running Tasks Together
Premium exercise. See plans
Testing with unittest
Premium exercise. See plans
Mocking and Isolation
Premium exercise. See plans
Logging
Premium exercise. See plans
Command Line Programs with argparse
Premium exercise. See plans
pathlib and Working With Files
Premium exercise. See plans
JSON and CSV in Practice
Premium exercise. See plans
Dates, Times and Time Zones
Premium exercise. See plans
Regular Expressions In Depth
Premium exercise. See plans
Databases from Python
Premium exercise. See plans
Threads and Processes
Premium exercise. See plans
Measuring and Improving Speed
Premium exercise. See plans
Packaging and pyproject.toml
Premium exercise. See plans
Calling Web APIs
Premium exercise. See plans
Python Best Practices
Premium exercise. See plans