Introduction to Python
Learn to write real Python programs from zero: variables, operators, strings, decisions and loops, lists and dictionaries, functions, modules and error handling. Each lesson pairs the theory (what the idea is and why it matters) with practice: real Python code that runs line by line in front of you, interactive tools you can drive yourself, and quizzes. Finish with a small project, then pass the final quiz to earn your certificate.
Theory
Each idea explained in plain words with everyday examples, tables of the key rules, and where you'll use it in real programs.
Practice
Real Python code that runs line by line, so you see every name and value change. Interactive tools, a final project, and a quiz per lesson.
Certificate
Score 80% or more on the final quiz to get a certificate with your name, ready to print, save as PDF or download as an image.
- 10 lessons
- 30 lesson quiz questions
- 10-question final quiz
- No installation needed to follow along
- Self-paced Β· works offline
How the course works
- Start with Getting Startedwhat Python is, how to install it, and your first program.
- Work through lessons 2 to 9 in orderread the idea, press Run or Step to watch the code, then take the lesson quiz.
- Build the final projectplay a small quiz game written with everything you learned, and see which lesson each part comes from.
- Take the final quizOne list of 10 simple questions covering every lesson. Score 8 of 10 or more to earn your certificate.
Colour key for the animations
When code runs in any lesson, the boxes in memory change colour to show what is happening at that moment:
- NormalA value stored under a name, not involved in the current line.
- Being usedThe value the current line is reading or working on right now.
- Just changedA name that was just created or given a new value.
- ResultThe answer: the value an expression or a step produced.
Course map
1. Getting Started (your first program)
Python is a programming language that reads almost like English, which makes it one of the easiest languages to learn and one of the most widely used.
A program is a list of instructions that the computer follows one line at a time, from top to bottom. Think of a recipe: each step is simple, and the order matters. Python's job is to read your recipe and carry it out.
print() shows text on the screen. It is a ready-made command; Python calls commands like this functions (lesson 7 shows how to write your own). Whatever you put inside its brackets is what it shows. Text goes inside quotes: print("Hello, World!"). Numbers don't need quotes: print(2 + 3) shows 5. Give print() several items separated by commas and it puts a space between them.Below is a tiny program saved in a file called hello.py (.py is the ending used for Python files). Press Step to run it one line at a time; the box under the picture explains each line.
What Python is and where people use it
Python is a general-purpose language: the same language is used for very different jobs. It's free, it runs on Windows, macOS and Linux, and it comes with a huge collection of ready-made tools.
| Area | What people build with Python |
|---|---|
| Data and AI | Data analysis, charts, machine learning and AI models |
| Web | Websites and web services (for example with Django or Flask) |
| Automation | Scripts that rename files, fill spreadsheets or send reports |
| Science and education | Experiments, simulations, and first programming courses |
Installing Python and choosing an editor
- Download Python from python.org and run the installer. On Windows, tick "Add Python to PATH", so you can start Python by typing
pythonin a terminal. - Open a terminal: a window where you type commands instead of clicking (on Windows it's called Command Prompt or PowerShell; on macOS it's Terminal). Check Python is installed:
python --version(on macOS or Linux it may bepython3 --version). - Pick a place to write code:
| Tool | Good for |
|---|---|
| VS Code | A free, light editor. Add the Python extension, then press βΆ to run a file. |
| PyCharm | A full Python IDE with smart hints and a debugger (the Community edition is free). |
| Jupyter | Notebooks made of cells: run small pieces one at a time. Popular in data science. |
| IDLE | A simple editor that comes with Python. Fine for your first steps. |
Running a script vs. the interactive shell (REPL)
There are two ways to run Python. A script is a file such as hello.py that you run all at once with python hello.py. The interactive shell, or REPL (Read, Evaluate, Print, Loop), starts when you type python on its own: you type one line at a time after the >>> prompt and see the answer immediately.
| Script | REPL | |
|---|---|---|
| Start it with | python hello.py | python |
| Runs | the whole file, top to bottom | one line at a time |
| Shows values | only what you print() | every expression's value |
| Best for | real programs you keep | quick experiments |
| Leave with | it ends by itself | exit() |
Where it shows up
- Every Python program you'll ever write is run the same way: line by line, top to bottom.
print()is the first tool for checking what your program is doing (you'll use it again for debugging in lesson 9).- The REPL is a handy calculator and the quickest way to test an idea.
2. Variables and Data Types (names for values)
A variable is a name that refers to a value. Every value has a type that decides what you can do with it.
Think of sticky labels on boxes. age = 21 puts the number 21 in a box and sticks the label age on it. Later, writing age means "the value in that box". Give the label to a new value and it simply moves.
The program below asks for your name and age, stores each answer under a name, and makes a few more variables of different types. Step through it now; the sections after it explain each new word.
abc too.
Variables and naming rules
- Names use letters, digits and
_, and can't start with a digit:score2is fine,2scoreis not. - No spaces or dashes: use
user_name, notuser nameoruser-name. - Names are case-sensitive:
ageandAgeare two different names. - You can't use Python's own reserved words, called keywords, such as
if,fororclass. - Choose names that say what the value means:
pricebeatsp.
Core types
| Type | What it holds | Examples |
|---|---|---|
int | Whole numbers | 7, -3, 2025 |
float | Numbers with a decimal point | 3.14, 1.75, 2.0 |
str | Text, inside quotes | "hello", '42' |
bool | Yes or no | True, False |
None (its type is called NoneType) | "No value yet" | None |
The type names are short: int = integer (a whole number), float = floating-point number (a number with a decimal point), str = string (a string of characters, in other words text), bool = Boolean (True or False, named after the mathematician George Boole).
Ask Python for the type of any value with type(): type(3.14) gives <class 'float'>.
Type conversion and user input
input() pauses the program, waits for the user to type something and press Enter, and always gives back a str, even if they typed digits. To do maths with it, convert it first with int() or float(). Use str() to turn a number into text.
"5" + 3 is a TypeError: Python won't add text to a number. Convert first: int("5") + 3 gives 8, and "5" + str(3) gives '53'.Where it shows up
- Every program stores data in variables: a score, a user's name, a price, a setting.
- Data from users, files and websites usually arrives as text and must be converted.
Nonemarks "not set yet", for example a value you haven't looked up.
3. Operators and Expressions (working values out)
An expression is anything Python can work out to a single value, like 2 + 3 * 4. Operators are the symbols that do the work.
It's the maths you know from school, with the same rule: multiplication happens before addition unless brackets say otherwise. Python also has operators that compare values and combine yes/no answers. Working out an expression's value is called evaluating it.
Pick an expression below and press Evaluate to watch Python work it out one operator at a time. The tables after the demo list every operator and the order they go in.
Arithmetic, comparison and logical operators
| Kind | Operator | Meaning | Example | Result |
|---|---|---|---|---|
| Arithmetic | + - | add, subtract | 7 + 2 | 9 |
* | multiply | 7 * 2 | 14 | |
/ | divide (always a float) | 7 / 2 | 3.5 | |
// | whole-number divide | 7 // 2 | 3 | |
% | remainder | 7 % 2 | 1 | |
** | power | 2 ** 3 | 8 | |
( ) | do this part first | (1 + 2) * 3 | 9 | |
| Comparison | == != < > <= >= | equal, not equal, less, greater⦠| 5 > 3 | True |
| Logical | and | True only if the values on both sides are True | True and False | False |
or | True if at least one of the two sides is True | True or False | True | |
not | flips True and False | not True | False |
= stores a value (x = 5). Two == asks a question (x == 5 gives True or False).Operator precedence
When an expression has several operators, Python does them in this order, from first to last. Operators on the same row go left to right. When in doubt, add brackets: they make your intent clear to readers too.
| Order | Operators |
|---|---|
| 1 | ( ) brackets |
| 2 | ** |
| 3 | * / // % |
| 4 | + - |
| 5 | == != < > <= >= |
| 6 | not, then and, then or |
Where it shows up
- Totals, averages and prices:
total = price * quantity. - Even or odd checks:
n % 2 == 0isTruefor even numbers. - Decisions (lesson 5):
if age >= 18 and has_ticket:.
4. Strings (working with text)
A string (str) is a sequence of characters (single letters, digits, spaces or symbols). Each character has a numbered position, so you can pick out one character or a slice (several characters in a row).
Think of a string as a row of letter tiles with numbers underneath. The number under a tile is that character's index (its position number). Counting starts at 0 on the left. Python also numbers from the right: -1 is the last tile, -2 the one before it.
To pick a position, write the index in square brackets: s[0] is the character at index 0. Type a word below, choose the numbers, and press a button.
Indexing and slicing
s[0]is the first character ands[-1]is the last.s[start:stop]takes characters fromstartup to but not includingstop:"Python"[0:2]is'Py'.- Leave a number out to mean "from the start" or "to the end":
s[:3],s[2:]. - A third number is the step:
s[::2]takes every second character,s[::-1]reverses the string. - Strings can't be changed in place:
s[0] = "J"is an error. Make a new string instead.
Common methods and f-strings
A method is a command that belongs to a value and works on it. You use it (programmers say you call it) by writing a dot after the value: text.upper(). A function is a named command such as print() or len(); lesson 7 covers them. String methods never change the original; they give back a new string.
Some methods work with a list: an ordered row of values in square brackets, like ['a', 'b'] (lesson 6 covers lists). Run the program below with your own text. Its last line uses an f-string, explained just below the table.
| Method | What it does | Example | Result |
|---|---|---|---|
strip() | removes spaces at both ends | " hi ".strip() | 'hi' |
split(sep) | cuts into a list of pieces | "a,b,c".split(",") | ['a', 'b', 'c'] |
sep.join(list) | glues a list back together, with the separator text sep between the items | "-".join(["a", "b"]) | 'a-b' |
replace(old, new) | swaps every old for new | "cat".replace("c", "b") | 'bat' |
upper() / lower() | changes the case | "Hi".lower() | 'hi' |
len(s) | counts characters (a built-in function, not a method) | len("cat") | 3 |
f before the quotes and write any value or expression inside { }: f"{name} scored {score}". It's the easiest way to build text from values, and you don't need str().Where it shows up
- Cleaning what users type:
answer.strip().lower()(you'll see this in the final project). - Reading data:
line.split(",")splits a line of a CSV file into fields. - Building messages and reports with f-strings.
5. Control Flow (decisions and loops)
Control flow decides which lines run and how many times. if makes decisions; for and while repeat work.
Think of a road with junctions and roundabouts. At a junction (if) you take one road depending on a condition. On a roundabout (a loop) you go around again and again until it's time to exit (break), and sometimes you skip ahead to the next lap (continue).
The program below counts from 1 upward. For each number it decides what to print (if / elif / else). Two settings let you skip one number (continue) or stop early (break). The sections after the demo explain each keyword.
Decisions and loops at a glance
A condition is an expression that is True or False, such as age >= 18 (lesson 3). An if checks one condition; elif and else add more choices underneath it. The lines under each one form its block, and they are indented (4 spaces): indentation is how Python knows what's inside.
Python checks the conditions from the top. It runs the block under the first condition that is True, then skips the rest. else runs only when none of them were true.
A loop repeats its block. Each pass through a loop is called a round (or iteration), and the indented lines that repeat are the loop's body. range(5) gives the numbers 0, 1, 2, 3, 4; range(1, 5) gives 1, 2, 3, 4.
| Statement | What it does |
|---|---|
if condition: | runs the indented block only when the condition is True |
elif condition: | "else if": checked only when every condition above was False |
else: | runs when nothing above was True |
for x in range(a, b): | repeats for each number from a up to (not including) b |
while condition: | repeats as long as the condition stays True |
break | leaves the loop immediately |
continue | skips the rest of this round and starts the next one |
Loops: for, while and range()
Use for when you know what to loop over: a range() of numbers, the items of a list (lesson 6), or the characters of a string. Use while when you repeat until something happens.
Here is a while loop that counts down from a number you choose and stops at zero.
while loop must change something so its condition eventually becomes False. count = count - 1 above means: work out count - 1 first, then store the result back in count, so it goes down by one each round. Forget that line and it would count forever. If that happens, press Ctrl+C to stop the program.Where it shows up
if: checking a password, a score, or whether a file exists.for: processing every item in a list, every line in a file, every row in a spreadsheet.while: game loops, menus and asking again until the user types a valid answer (see the final project).
6. Data Structures (list, tuple, dict, set)
Python has four built-in (ready to use, nothing to install) ways to keep many values together, called collections. Each one is good at a different job.
A list is like a shopping list: ordered, and you can add or cross off items. A tuple (a maths word for a fixed group of values) is like a date of birth: fixed once written. A dict (short for dictionary) is like a phone book: you look up a value (the phone number) by its key (the person's name). A set is like a bag of unique stickers: no duplicates allowed.
Below, four collections are already in memory. Each button runs one line of code on them, and the box under the picture explains what that line did.
fruits Β· list Β· ordered, changeable
point Β· tuple Β· ordered, fixed
ages Β· dict Β· key β value
colors Β· set Β· unique items
list, tuple, dict and set
Ordered means the items stay in the order you put them in (not that they get sorted).
| Type | Written as | Ordered? | Can change? | Duplicates? | Get an item |
|---|---|---|---|---|---|
| list | ["a", "b"] | yes | yes | yes | items[0] |
| tuple | (3, 4) | yes | no | yes | point[0] |
| dict | {"Ada": 36} | keeps the order keys were added | yes | keys are unique | ages["Ada"] |
| set | {"red", "blue"} | no | yes | no | "red" in colors |
When to use each one
Pick the collection you'd reach for in each situation, then check the answer.
List comprehensions (a light intro)
A list comprehension builds a new list in one line: [n * n for n in range(1, 6)] reads as "n times n, for each n in range(1, 6)". It does exactly what the three-line loop does. Step through both below.
Where it shows up
- list: rows of data, to-do items, scores, anything in an order you can change.
- tuple: fixed pairs such as coordinates
(x, y)or RGB colours. - dict: settings, word counts, a user's profile (
{"name": ..., "email": ...}), and JSON data from the web. - set: removing duplicates and fast "have I seen this?" checks.
7. Functions (reusable blocks of code)
A function is a named block of code that does one job. You define it once with def and call it as many times as you like.
Think of a coffee machine. You press a button and give it inputs (the cup size). It does its work inside, then hands you a result (the coffee). You don't need to know what happens inside to use it, and you can use it again and again.
The program below defines two functions, greet and area, and then uses (calls) them. Step through it: a purple box of the function's own names appears for each call. The sections after the demo explain what you see.
Defining and calling functions
def name(parameters):starts a definition. The indented lines below are the function's body.- Defining a function does not run it. The body runs only when you call it:
greet("Ada"). - Calling pauses the caller, jumps into the function, and comes back when the function finishes.
Parameters, default values and return values
| Term | Meaning | In the example |
|---|---|---|
| Parameter | a name in the definition that receives a value | name, punctuation |
| Argument | the actual value you pass when calling | "Ada" |
| Default value | used when the caller leaves that argument out | punctuation="!", height=1 |
| Return value | the result return sends back to the caller | return message |
print() only shows a value on the screen. return hands the value back so the caller can store it and use it. A function with no return gives back None.Scope: local vs. global
Names created inside a function are local: they exist only while that call runs, in its own box of names (shown in purple above), and disappear when it returns. Names created at the top level of the file are global. A function can read a global name (like greeting), but the code outside can't see the function's local names.
return. Changing global variables from inside functions (with the global keyword) makes programs harder to follow.Where it shows up
- Everywhere:
print(),len()andinput()are functions someone else wrote. - Splitting a program into small named steps, as the final project does with
ask(),play()andmain(). - Avoiding copy-and-paste: fix a bug once inside the function and every call gets the fix.
8. Modules (the standard library)
A module is a file of ready-made Python code. import loads it so you can use its functions instead of writing them yourself.
Think of a toolbox. Python comes with a big one, the standard library, with a drawer for each kind of job: math for calculations, random for chance, datetime for dates. import opens a drawer; it's free and already installed.
The program below imports modules in three different ways (the Import styles table after it explains each one). Each button runs one line.
What a module is and why we use import
- A module is just a
.pyfile. Every file you write is a module too, so you can import your own code. - Modules keep code organised and save you from reinventing things like square roots or calendars.
- Put imports at the top of your file, so readers see what the program depends on.
Import styles
| You write | Then you use | Good when |
|---|---|---|
import math | math.sqrt(16) | the usual choice: it's clear where sqrt comes from |
from math import sqrt | sqrt(16) | you use one or two names a lot |
import datetime as dt | dt.date.today() | the module name is long: as gives it a short nickname |
from math import *. It dumps every name from the module into your program, so it's hard to tell where a name came from.Practical use of math, random and datetime
| Module | Useful names | Example |
|---|---|---|
math | pi, sqrt(), floor(), ceil() | circle area: math.pi * r ** 2 |
random | randint(a, b), choice(list), shuffle(list), sample(list, k) | dice games, picking a random question |
datetime | date.today(), timedelta(days=7), datetime.now() | due dates, ages, timestamps |
Where it shows up
- Real programs import a lot: reading files (
os,pathlib), the web (urllib), data (json,csv). - Beyond the standard library,
pip installadds packages from the internet, such asrequestsorpandas. You import them the same way.
9. Errors and Exceptions (when things go wrong)
Errors are normal: every programmer sees them all day. Python tells you what went wrong and where, and try / except lets your program recover instead of crashing. When Python hits a problem while running, it stops and reports an error. Python calls this an exception, and says the line raised it.
Think of a smoke alarm. An exception is the alarm going off: something unexpected happened. A traceback tells you which room it came from, and an except block is your plan for what to do when the alarm rings.
Reading error messages and tracebacks
Click each line of the traceback to see what it means. The program it came from is on the right. It uses two things you haven't met yet: sum(items) adds up all the numbers in a list, and if not items: is True when the list is empty (an empty list counts as False).
| Error | Usually means | Example |
|---|---|---|
SyntaxError | the code isn't written correctly (a missing colon, bracket or quote) | if x > 3 |
NameError | a name that doesn't exist yet, often a typo | prnt("hi") |
TypeError | the wrong type for the job | "5" + 3 |
ValueError | right type, but a bad value | int("abc") |
IndexError | a position that doesn't exist | [1, 2][5] |
KeyError | a dict key that doesn't exist | {"a": 1}["b"] |
ZeroDivisionError | dividing by zero | 10 / 0 |
try / except / finally
Put code that might fail inside try. If an error happens, Python jumps straight to the matching except block instead of crashing. finally runs at the end either way. Try a good input, then some text, then a zero.
Basic debugging
- Read the last line of the traceback, then go to the line number it points to.
- Print what you think you know: add
print(x, type(x))just before the failing line to check names and types. - Make it smaller: run the failing piece on its own in the REPL.
- Use a debugger: in VS Code or PyCharm, click next to a line number to set a breakpoint, then run step by step and watch the variables, just like the Step button in this course.
- Explain it out loud, line by line ("rubber duck debugging"). You'll often spot the problem as you speak.
Where it shows up
- Checking user input: ask again when someone types letters instead of a number (the final project does this).
- Files that might be missing, and network calls that might fail.
finally: always closing a file or connection, even after an error.
10. Final Project (a quiz game)
Time to put it all together: a small quiz game that uses variables, strings, loops, a list of dicts (dictionaries), functions, two modules and error handling.
Play it below. The game really runs: type your answers into the console and watch each line of the program light up as it executes. Then read the code and the table underneath to see which lesson every part comes from.
Which lesson each part comes from
| In the game | What it does | Lesson |
|---|---|---|
import random, import datetime as dt | random question order, today's date | 8. Modules |
QUESTIONS = [{"q": β¦, "a": β¦}, β¦] | a list of dictionaries holds the questions | 6. Data Structures |
def ask(), def play(), def main() | each function does one job and returns a result | 7. Functions |
for item in questions, while True, break, if / else | repeats the rounds, asks again until the input is valid | 5. Control Flow |
try / except ValueError | no crash when the player types letters instead of a number | 9. Errors |
answer.strip().lower(), f-string | tidies the answer, builds the score message | 4. Strings |
==, <=, score / rounds * 100 | checks answers and works out the percentage | 3. Operators |
input(), int(), score = 0 | reads the player's answers, keeps the score | 2. Variables & Types |
New pieces in the game
The game uses a few small things the lessons didn't show:
score += 1is short forscore = score + 1.while True:repeats forever on purpose. Thebreakinside it is the way out: it runs once the player types a valid number.1 <= rounds <= len(QUESTIONS)meansroundsis at least 1 and at most 4 (the number of questions).random.sample(QUESTIONS, rounds)picks that many different questions in a random order, andround()rounds a number to the nearest whole number.
Make it your own
- Quiz game: add your own questions to
QUESTIONS, or a time limit usingdatetime. - To-do app in memory: a
while Truemenu withadd,list,doneandquit, storing tasks in a list of dicts. - Simple calculator: ask for two numbers and an operator, use
if/elifto pick the operation, and catchValueErrorandZeroDivisionError.
quiz_game.py, run it with python quiz_game.py, and change one thing at a time. Breaking it on purpose and reading the traceback is a great way to learn.Python cheat sheet
Everything from the course on one page. Filter by topic to revise before the final quiz.
Final quiz & certificate
This is the last step of the course: one list of 10 questions covering every lesson. After each answer you'll see the correct option and why it's right. Score 80% or more (8 of 10) to earn a certificate with your name.