Zhimalab
🐍
Python in 21 Days
Starting the Python runtime…
Python in 21 Days
Welcome to Python in 21 Days! This tutorial assumes you already have some programming background (e.g. you have seen C or Java), so we skip questions like "what is a variable" and focus on what makes Python unique.
21 days, from basic syntax to object-oriented programming, generators, and a capstone project. Each lesson has runnable code (powered by Pyodide — Python runs right in your browser) and hands-on exercises.
How to use: Pick a lesson from the sidebar on the left. Each lesson includes explanations, runnable code samples, and exercises. Click "Mark complete" when you finish to track your progress.
Hello, Python
Welcome to Python in 21 Days! This tutorial assumes you already have some programming background (e.g. you have seen C or Java), so we skip questions like "what is a variable" and focus on what makes Python unique.
Python is famous for being concise. The classic first line of code only needs a single
print(). Click the Run button on the code block below to try it: hello.py
Python needs no
main() function, no semicolons, no header files — just write and run. Variables don't need type declarations either; assignment creates them: Variables & types
Key point: Python is
dynamically typed — a variable's type is determined at runtime and may change at any time. Use type() to inspect any variable's type.input() reads user input (returns a string), and the f-string (formatted string) is the recommended way to compose strings in Python 3.6+:
f-string intro
Exercise
Create a variable
city assigned to "Beijing" and a variable temp assigned to 26, then use an f-string to print: Beijing today's temperature is 26 degrees. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Numbers & strings
Python has three numeric types:
int (integers, unbounded), float (floating point), and complex (complex numbers). The arithmetic operators are similar to C, but / always returns a float and // is integer division. Arithmetic
Strings
Strings can use single quotes, double quotes, or triple quotes. Triple quotes can span multiple lines. Strings support
* repetition and + concatenation, but f-strings are more elegant. String operations
Slicing is a core Python feature.
s[start:stop:step] is half-open. s[::-1] reverses a string — the most classic Python trick.Exercise
Given the string
s = "Hello, Python!", use slicing to extract "Python" and print it. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Booleans & operators
Python's booleans are
True and False (capitalized). Comparison operators: == != < > <= >=. Logical operators are the English words and, or, not — not && || !. Booleans & logic
Truthiness: the following values are all "false":
0, 0.0, "", [], {}, None. Everything else is "true". Truthiness
is vs ==:
is tests whether two references point to the same object (memory address); == tests whether values are equal. For value comparison, use ==.Exercise
Write a function
is_leap_year(year) that decides whether a given year is a leap year. Rule: divisible by 4 but not by 100, or divisible by 400. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Conditionals
Python uses
if / elif / else for branching. There is no switch-case (3.10+ adds match-case). Important: Python uses indentation to mark code blocks; an indentation error is a syntax error. if/elif/else
Conditional expression (ternary):
value1 if condition else value2, equivalent to C's condition ? value1 : value2. Ternary & match
Indentation rule: use 4 spaces consistently (PEP 8 standard).
pass is a no-op placeholder, used where the implementation is not yet written.Exercise
Write a function
classify(num) that returns "positive", "negative", or "zero". Then test with 5, -3, 0. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
while loops
A
while loop is similar to C, but Python has no do-while. break exits the loop, continue skips the current iteration. An else block can follow a loop — it runs when the loop ends normally (i.e. not via break). while loop
while-else
while-else is a Python specialty: the
else block runs when the loop completes without a break. Great for "search" scenarios — break when found, run else when not.Exercise
Use a
while loop to compute 2^10 (without using the ** operator); store the result in a variable named result and print it. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
for loops & range
Python's
for is not C's for(init;cond;inc) — it is for-in iteration, walking each element of an iterable directly. range() generates integer sequences. for loop
zip & nested loops
Python has no C-style for loop. Use
range() when you need indices; enumerate() when you need index + value; zip() for parallel iteration.Exercise
Use a
for loop with range() to print row 5 of a multiplication table: 1x5=5 2x5=10 3x5=15 4x5=20 5x5=25 Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Lists — basics
A list (
list) is Python's most common data structure — mutable, ordered, holds any type. Think of it as a blend of C arrays and linked lists, but far more flexible. List operations
List sorting
sorted() vs .sort():
sorted() returns a new list and leaves the original unchanged; .sort() sorts in place and returns None.Exercise
Given the list
nums = [5, 3, 8, 1, 9, 2, 7], use sorted() to sort it in descending order; store the result in a variable named result and print it. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
List comprehensions
A list comprehension is one of Python's most elegant features — build a list in a single line. For someone with a C/Java background, this is the first lesson in "Pythonic" thinking.
List comprehension
Nested & dict comprehensions
Comprehension syntax:
[expression for variable in iterable if condition]. If it spans more than two lines, use a regular loop instead.Exercise
Use a list comprehension to generate the squares of all even numbers from 1 to 20; the result should be
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]. Store it in a variable named result. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Tuples & unpacking
A tuple (
tuple) is an immutable list. Once created, it cannot be modified. Its uses: fixed data (e.g. coordinates), multiple function return values, and as dictionary keys (lists cannot be keys). Tuples & unpacking
Multiple returns
Tuple vs list — when to use which? Use a tuple when the data won't change (safer, faster, hashable). Use a list when you need to add/remove/modify elements.
Exercise
Use tuple unpacking to swap the values of
a (currently 100) and b (currently 200) in one step, so that a=200 and b=100. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Dictionaries
A dictionary (
dict) is Python's most powerful data structure — key-value mapping with O(1) lookup. Python 3.7+ guarantees insertion order. Keys must be immutable types (str, int, tuple); lists and dicts cannot be keys. Dict operations
Dict comprehension & word count
dict.get(key, default) is the safe way to access a dictionary — when the key is absent it returns the default instead of raising an error.
Exercise
Given the string
text = "apple banana apple cherry banana apple", count occurrences of each word and store the result in a dictionary named freq. Expected: {'apple': 3, 'banana': 2, 'cherry': 1} Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Sets
A set (
set) is an unordered collection of unique elements. Core uses: deduplication and set operations (union, intersection, difference, symmetric difference). Lookup is O(1), as fast as a dict. Set operations
Set applications
Set operators:
| union, & intersection, - difference, ^ symmetric difference. More concise than calling methods.Exercise
Given two lists
a = [1, 2, 3, 4, 5] and b = [4, 5, 6, 7, 8], use set operations to find their common elements; store the result in a variable named common. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Functions — basics
Python uses
def to define a function. Unlike C/Java: parameters may have default values, can be passed by name, and can accept a variable number of arguments. Functions are first-class objects — they can be assigned to variables and passed as arguments. Function definitions
Variadic arguments
*args collects extra positional arguments as a tuple; **kwargs collects extra keyword arguments as a dict. Parameter order:
def f(required, default, *args, **kwargs).Exercise
Write a function
power(base, exp=2) that computes base raised to exp. exp defaults to 2 (i.e. square). Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Lambda & higher-order functions
lambda is an anonymous function — defined in one line, ideal for short throwaway functions. map(), filter(), sorted() and other higher-order functions are often paired with lambda. That said, list comprehensions are usually more Pythonic than map/filter. lambda expression
map / filter / reduce
Pythonic advice: prefer list comprehensions over map/filter for simple operations — they read better. Reserve lambda for short one-line functions.
Exercise
Given the list
words = ["banana", "apple", "cherry", "date"], use sorted() with a lambda to sort by string length; store the result in a variable named result. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Strings — advanced
Python's string methods are very rich. Strings are immutable — every "modification" returns a new string.
String methods
String formatting
Exercise
Given the string
s = "hello world python", capitalize the first letter of each word so the result is "Hello World Python". Store it in a variable named result. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
File I/O
File I/O uses the
open() function. Always use the with statement — it closes the file automatically, even if an error occurs, preventing resource leaks. Modes: 'r' read, 'w' write (overwrite), 'a' append. File read/write
The with statement is a context manager, equivalent to try-finally but cleaner.
with open(...) as f: automatically calls f.close() when the block ends, even if an exception is raised. JSON read/write
Exercise
Write the string
"Python is the best language" to the file /tmp/quote.txt, then read it back into a variable named content and print it. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Exceptions
Python uses
try/except/else/finally to handle exceptions. except can specify an exception type. Do not use a bare except: — it hides bugs. try/except/else/finally
raise & custom exceptions
Exception-handling principles: ① only catch exceptions you expect; ② handle them, don't just
pass; ③ put the "normal path" in the else block; ④ use finally for resource cleanup.Exercise
Write a function
safe_divide(a, b) that returns a / b. If b is 0, return the string "Error: division by zero" (do not raise). Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Classes & objects
Python is object-oriented, but unlike Java it does not force everything into classes.
class defines a class, __init__ is the constructor, self is Python's equivalent of Java's this. The first parameter of an instance method is always self. Class definition
__str__ vs __repr__:
__str__ is user-facing (called by print); __repr__ is developer-facing (called in interactive sessions). classmethod, staticmethod, property
Exercise
Define a
Circle class with a radius attribute. Method area() returns the area (πr²), method perimeter() returns the circumference (2πr). Use math.pi. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Inheritance & magic methods
Python supports single and multiple inheritance.
super() calls the parent class method. Magic methods (dunder methods) start and end with double underscores; they define object behavior — operator overloading, iteration, comparison, etc. Inheritance & polymorphism
Operator overloading
Common magic methods:
__eq__(==), __add__(+), __len__(len()), __getitem__([]), __iter__(for loop).Exercise
Define a
Book class with title and author attributes. Implement __str__ to return '"title" by author' (title wrapped in ASCII double quotes, then a space, the word "by", a space, and the author). Implement __eq__ to compare both title and author for equality. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Modules & standard library
Python's standard library is extremely rich — "batteries included".
import imports a module; from ... import ... imports specific objects. Every .py file is a module. Standard library
collections & itertools
Import styles:
import mod (call via mod.func()); from mod import func (call func() directly); import mod as m (alias).Exercise
Use the
random module to generate 5 unique random integers between 1 and 100; store them in a list named numbers and print it. Use random.sample(). Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Iterators & generators
Generators are a core Python feature — lazy evaluation: they don't produce all values at once, but yield them on demand. When processing large data streams, generators save huge amounts of memory.
Generators
Generators — advanced
yield vs return:
return ends the function; yield "pauses" it — the next call to next() resumes from where it left off.Exercise
Write a generator function
even_stream() that produces an infinite sequence of even numbers: 0, 2, 4, 6, 8, ... Use islice to take the first 5 and store them in a list named result. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
Capstone: student manager
On the final day, tie everything together — classes, lists, dicts, file I/O, exception handling — and build a student grade manager. This is a typical small Python project.
Requirements: ① add a student (name, age, score); ② list all students; ③ sort by score; ④ compute average and max; ⑤ save to a JSON file.
Student manager
Congratulations on finishing the 21-day Python journey! You now have the core syntax, data structures, functions, OOP, file I/O, exceptions, and generators under your belt. Next you can explore: web development (Django/Flask), data analysis (Pandas/NumPy), automation scripts, machine learning, and more.
Exercise
Using the
StudentManager class above, create a manager, add 3 students (Alice 90, Bob 85, Carol 95), then call stats() and store the returned dict in a variable named info. Your code
Read the explanation above carefully, then give it a try. If you are still stuck, try breaking the code into smaller steps.
🎉
Congratulations on finishing the course!
You have mastered the core of Python. Keep exploring the wider programming world!