🐍 Intro to Python
Free self-paced course Β· Certificate on completion

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

  1. Start with Getting Startedwhat Python is, how to install it, and your first program.
  2. Work through lessons 2 to 9 in orderread the idea, press Run or Step to watch the code, then take the lesson quiz.
  3. Build the final projectplay a small quiz game written with everything you learned, and see which lesson each part comes from.
  4. Take the final quizOne list of 10 simple questions covering every lesson. Score 8 of 10 or more to earn your certificate.
Tip for each lesson: before you press Step, guess what the next line will do. Use the Animation speed slider at the top to slow things down. There's no time limit, and you can retake any quiz. When you install Python (lesson 1), type the examples yourself too.

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.

First program: 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.

AreaWhat people build with Python
Data and AIData analysis, charts, machine learning and AI models
WebWebsites and web services (for example with Django or Flask)
AutomationScripts that rename files, fill spreadsheets or send reports
Science and educationExperiments, simulations, and first programming courses

Installing Python and choosing an editor

  1. Download Python from python.org and run the installer. On Windows, tick "Add Python to PATH", so you can start Python by typing python in a terminal.
  2. 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 be python3 --version).
  3. Pick a place to write code:
ToolGood for
VS CodeA free, light editor. Add the Python extension, then press β–Ά to run a file.
PyCharmA full Python IDE with smart hints and a debugger (the Community edition is free).
JupyterNotebooks made of cells: run small pieces one at a time. Popular in data science.
IDLEA 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.

Terminal Β· python
$ python
ScriptREPL
Start it withpython hello.pypython
Runsthe whole file, top to bottomone line at a time
Shows valuesonly what you print()every expression's value
Best forreal programs you keepquick experiments
Leave withit ends by itselfexit()

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.

Try an age like abc too.

Variables and naming rules

  • Names use letters, digits and _, and can't start with a digit: score2 is fine, 2score is not.
  • No spaces or dashes: use user_name, not user name or user-name.
  • Names are case-sensitive: age and Age are two different names.
  • You can't use Python's own reserved words, called keywords, such as if, for or class.
  • Choose names that say what the value means: price beats p.

Core types

TypeWhat it holdsExamples
intWhole numbers7, -3, 2025
floatNumbers with a decimal point3.14, 1.75, 2.0
strText, inside quotes"hello", '42'
boolYes or noTrue, 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.

Try:
Common mistake: "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.
  • None marks "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.

Evaluating step by step
Output
(nothing printed yet)

Arithmetic, comparison and logical operators

KindOperatorMeaningExampleResult
Arithmetic+ -add, subtract7 + 29
*multiply7 * 214
/divide (always a float)7 / 23.5
//whole-number divide7 // 23
%remainder7 % 21
**power2 ** 38
( )do this part first(1 + 2) * 39
Comparison== != < > <= >=equal, not equal, less, greater…5 > 3True
LogicalandTrue only if the values on both sides are TrueTrue and FalseFalse
orTrue if at least one of the two sides is TrueTrue or FalseTrue
notflips True and Falsenot TrueFalse
= vs ==: one = 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.

OrderOperators
1( ) brackets
2**
3* / // %
4+ -
5== != < > <= >=
6not, then and, then or

Where it shows up

  • Totals, averages and prices: total = price * quantity.
  • Even or odd checks: n % 2 == 0 is True for 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.

s Β· top: index from the right Β· bottom: index from the left
Result

Indexing and slicing

  • s[0] is the first character and s[-1] is the last.
  • s[start:stop] takes characters from start up to but not including stop: "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.

MethodWhat it doesExampleResult
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-strings: put an 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.

StatementWhat 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
breakleaves the loop immediately
continueskips 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.

Infinite loops: a 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.

Memory Β· four collections

fruits Β· list Β· ordered, changeable

point Β· tuple Β· ordered, fixed

ages Β· dict Β· key β†’ value

colors Β· set Β· unique items

Output
(nothing printed yet)

list, tuple, dict and set

Ordered means the items stay in the order you put them in (not that they get sorted).

TypeWritten asOrdered?Can change?Duplicates?Get an item
list["a", "b"]yesyesyesitems[0]
tuple(3, 4)yesnoyespoint[0]
dict{"Ada": 36}keeps the order keys were addedyeskeys are uniqueages["Ada"]
set{"red", "blue"}noyesno"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

TermMeaningIn the example
Parametera name in the definition that receives a valuename, punctuation
Argumentthe actual value you pass when calling"Ada"
Default valueused when the caller leaves that argument outpunctuation="!", height=1
Return valuethe result return sends back to the callerreturn message
print vs. return: 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.

Prefer passing values in as parameters and getting them back with return. Changing global variables from inside functions (with the global keyword) makes programs harder to follow.

Where it shows up

  • Everywhere: print(), len() and input() are functions someone else wrote.
  • Splitting a program into small named steps, as the final project does with ask(), play() and main().
  • 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.

Global names Β· and what each module contains
Output
(nothing printed yet)

What a module is and why we use import

  • A module is just a .py file. 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 writeThen you useGood when
import mathmath.sqrt(16)the usual choice: it's clear where sqrt comes from
from math import sqrtsqrt(16)you use one or two names a lot
import datetime as dtdt.date.today()the module name is long: as gives it a short nickname
Avoid 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

ModuleUseful namesExample
mathpi, sqrt(), floor(), ceil()circle area: math.pi * r ** 2
randomrandint(a, b), choice(list), shuffle(list), sample(list, k)dice games, picking a random question
datetimedate.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 install adds packages from the internet, such as requests or pandas. 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).

Terminal Β· python shop.py
Read a traceback from the bottom up. The last line names the error and says what went wrong. The lines above show the path that led there, ending at the exact line that failed.
ErrorUsually meansExample
SyntaxErrorthe code isn't written correctly (a missing colon, bracket or quote)if x > 3
NameErrora name that doesn't exist yet, often a typoprnt("hi")
TypeErrorthe wrong type for the job"5" + 3
ValueErrorright type, but a bad valueint("abc")
IndexErrora position that doesn't exist[1, 2][5]
KeyErrora dict key that doesn't exist{"a": 1}["b"]
ZeroDivisionErrordividing by zero10 / 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

  1. Read the last line of the traceback, then go to the line number it points to.
  2. Print what you think you know: add print(x, type(x)) just before the failing line to check names and types.
  3. Make it smaller: run the failing piece on its own in the REPL.
  4. 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.
  5. 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.

Terminal Β· python quiz_game.py
$ python quiz_game.py

Which lesson each part comes from

In the gameWhat it doesLesson
import random, import datetime as dtrandom question order, today's date8. Modules
QUESTIONS = [{"q": …, "a": …}, …]a list of dictionaries holds the questions6. Data Structures
def ask(), def play(), def main()each function does one job and returns a result7. Functions
for item in questions, while True, break, if / elserepeats the rounds, asks again until the input is valid5. Control Flow
try / except ValueErrorno crash when the player types letters instead of a number9. Errors
answer.strip().lower(), f-stringtidies the answer, builds the score message4. Strings
==, <=, score / rounds * 100checks answers and works out the percentage3. Operators
input(), int(), score = 0reads the player's answers, keeps the score2. Variables & Types

New pieces in the game

The game uses a few small things the lessons didn't show:

  • score += 1 is short for score = score + 1.
  • while True: repeats forever on purpose. The break inside it is the way out: it runs once the player types a valid number.
  • 1 <= rounds <= len(QUESTIONS) means rounds is at least 1 and at most 4 (the number of questions).
  • random.sample(QUESTIONS, rounds) picks that many different questions in a random order, and round() rounds a number to the nearest whole number.

Make it your own

  • Quiz game: add your own questions to QUESTIONS, or a time limit using datetime.
  • To-do app in memory: a while True menu with add, list, done and quit, storing tasks in a list of dicts.
  • Simple calculator: ask for two numbers and an operator, use if / elif to pick the operation, and catch ValueError and ZeroDivisionError.
Copy the code into 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.