Eight short lessons for someone who has never written a program. Run your first line in the browser, then learn values, text, decisions, loops, lists, functions and how to read an error message. Every example runs on this page, with nothing to install.
What you need first
No programming experience. You do not need to know what a variable or a loop is. Each lesson explains its words when they first appear.
A computer, tablet or phone with a modern web browser. The first time you press Run, you need an internet connection, because the page downloads Python (about 10 MB, once only).
School arithmetic: adding, subtracting, multiplying and dividing numbers, and comparing which one is bigger.
To run programs on your own computer, which is optional at first: a Windows, macOS or Linux computer where you are allowed to install software.
Time: plan about half an hour per lesson if you type each example yourself and do the self-checks.
Set up your computer
Optional at first: the examples below also run on this page.
You do not need to install anything to start. Every Run button in the lessons runs a real copy of Python inside your browser. Come back to this section when you want to save a program in a file and run it on your own computer.
The plan is short. Install Python. Ask it for its version number, which proves that it works. Then save a one-line program in a file called hello.py and run it. A terminal is a window where you type a command and read the reply. Windows calls it PowerShell. macOS calls it Terminal.
Use Python 3.10 or newer. The newest version on the python.org download page is a good choice. Python 2 was retired long ago and its programs are written differently. If a lesson shows something different from what you see, check your version first.
One small difference: on Windows you type python, and on macOS and Linux you type python3. Below, each system tells you which one to use.
Windows
Open python.org/downloads in your browser. Click Download Python install manager. Open the file you downloaded (its name ends in .msix) and click Install. The Python documentation recommends this for Windows 10 and newer. You can also get the same program from the Microsoft Store: search for Python Install Manager.
Open a new terminal. Click Start, type PowerShell and press Enter. If a terminal was already open before the install, close it and open a new one. An old window does not notice programs installed after it started.
Type the line below and press Enter. The first time, the install manager may download Python itself and ask you to confirm. Accept the default answers and wait. python --version
In File Explorer, make a new folder called python-practice, for example on your Desktop.
Open Notepad (Start, type Notepad). Type this one line: print("Hello, Python!") Click File, then Save as. Open the Save as type menu and choose All files. Type hello.py as the file name, choose your python-practice folder and click Save.
In File Explorer, open the python-practice folder. Click the address bar at the top, type powershell and press Enter. A terminal opens inside that folder. Type: python hello.py You should see Hello, Python! on the next line. If Windows says the file does not exist, it may be called hello.py.txt. In File Explorer click View, then Show, then File name extensions, and rename the file.
Check it worked
python --version
You should see A line such as Python 3.15.2. Any version from 3.10 up is fine, and your numbers may differ.
macOS
Open python.org/downloads in your browser and download the macOS installer (a .pkg file). Open it and follow the steps. It asks for your Mac password, because Python is installed for every user of the computer. Your Mac already has a small copy of Python made by Apple, but it is old and meant for Apple's own tools. Use the one from python.org.
Open Terminal: press Command and Space, type Terminal and press Enter. If a Terminal window was already open during the install, open a new one.
Type the line below and press Enter. On macOS the command is python3, not python. If a pop-up offers to install developer tools, click Cancel and check that step 1 finished. python3 --version
Make a folder and a file from inside the Terminal. Type these lines one at a time, pressing Enter after each: mkdir python-practice cd python-practice nano hello.py The last line opens nano, a small text editor that runs inside the Terminal.
Type this one line into nano: print("Hello, Python!") Then press Control and O (the letter), press Enter to confirm the file name, and press Control and X to leave nano.
Run the program: python3 hello.py You should see Hello, Python! on the next line.
Check it worked
python3 --version
You should see A line such as Python 3.15.2. Any version from 3.10 up is fine, and your numbers may differ.
Linux
Most Linux systems already include Python 3, so do the check in step 3 first. If it fails, install Python with your package manager. On Debian and Ubuntu: sudo apt update sudo apt install python3 On Fedora: sudo dnf install python3 On Arch Linux: sudo pacman -S python The sudo command asks for your password. Nothing appears on the screen while you type it. That is normal.
Open a terminal. On many desktops, pressing Control, Alt and T opens one. Otherwise search your applications for Terminal.
Type the line below and press Enter. python3 --version
Make a folder and a file. Type these lines one at a time, pressing Enter after each: mkdir python-practice cd python-practice nano hello.py The last line opens nano, a small text editor that runs inside the terminal.
Type this one line into nano: print("Hello, Python!") Then press Control and O (the letter), press Enter to confirm the file name, and press Control and X to leave nano.
Run the program: python3 hello.py You should see Hello, Python! on the next line.
Check it worked
python3 --version
You should see A line such as Python 3.12.3. Any version from 3.10 up is fine. An older version still runs the code, but prints less helpful error messages.
If you see an error
python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program.
Windows cannot find Python. Either it is not installed, or this terminal window was open before you installed it. Close the terminal, open a new one and try again.
If it still fails, repeat Windows step 1. Then open Start, search for Manage app execution aliases, and check that the Python (default) switches are on. You can also try py --version, which sometimes works when python does not.
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
Before Python is installed, Windows puts a placeholder shortcut under the name python. Install Python as in Windows step 1, open a new terminal and try again. If the message stays, open Manage app execution aliases and make sure the Python (default) switches are on.
zsh: command not found: python
macOS has no command called python. Type python3 instead: python3 --version, and python3 hello.py.
bash: python: command not found
On Linux the command is python3. Some systems print Command 'python' not found, did you mean python3, which says the same thing. On Debian and Ubuntu you can also run sudo apt install python-is-python3, which makes python work as well.
zsh: command not found: python3
Python 3 is not installed, or the install did not finish. On macOS, repeat step 1 and open a new Terminal window. On Linux, install it with your package manager (Linux step 1); bash prints bash: python3: command not found. On Windows, type python, not python3.
python3: can't open file '/home/mia/hello.py': [Errno 2] No such file or directory
Python works, but it cannot find your file in the folder where the terminal is. First check the folder. List the files with ls on macOS and Linux, or dir on Windows, and look for hello.py. If you do not see it, move into the folder with cd python-practice, or open a terminal from inside the folder as in Windows step 6.
Then check the spelling. The name must be exactly hello.py, not Hello.py and not hello.py.txt. On Windows, turn on File name extensions in File Explorer (View, Show) to see the real name.
IndentationError: unexpected indent
A line starts with spaces that Python did not expect. Python uses the spaces at the start of a line to group lines together. Delete the extra spaces so that the line lines up with the line above. Only a line that follows a line ending in a colon should be moved right, by four spaces.
The opposite message, IndentationError: expected an indented block after 'if' statement on line 2, means a line ending in a colon has nothing indented under it. Add four spaces. Never mix Tab characters and spaces; if you do, Python reports TabError. Lesson 4 explains indentation.
SyntaxError: invalid syntax
Python cannot understand how a line is written, so it ran nothing at all. Look at the line number and the ^ marks under the line. The mistake is at that spot or just before it. Common causes are a missing colon, a missing quote or bracket, curly quotes pasted from a document, and a Python 2 style print without brackets.
Other messages that begin with SyntaxError, such as SyntaxError: unterminated string literal (detected at line 1), are more specific and say what is wrong. Lesson 8 shows how to read them step by step.
01
What a program is, and your first line
Goal run a Python program on this page and change what it says.
A program is a list of instructions for a computer. A computer cannot guess what you mean, so every instruction must be written in a language it understands. Python is one such language.
The computer follows the instructions one at a time, from the top line to the bottom line. Running a program means asking the computer to follow them. What the program shows you is its output.
Your first instruction is print. It makes Python show something on the screen. You put what to show inside round brackets. If it is text, you wrap the text in quote marks. The quote marks tell Python that these words are text and not an instruction.
Now run one. Press the Run button under the code below. The first time, the page downloads Python, which takes a few seconds. The output appears under the code. Then press Edit code, change the words between the quote marks, and press Run again. Nothing you type here can harm your computer, and Reset puts the original code back.
New words
program
A list of instructions for a computer.
Python
A programming language with a readable style.
run
Ask the computer to follow the instructions of a program.
output
What a program shows or writes when it runs.
print
A Python instruction that shows what you give it.
quote marks
The " " around text. They tell Python that the words are text.
Worked example
Python 3
print("Hello, Leon!")
Predict the output first, then show it
Expected output
Hello, Leon!
Step by step
Python reads the line. The word print is something Python already knows how to do.
The round brackets ( ) hold what print should show. Whatever sits between them is handed to print.
The quote marks tell Python that Hello, Leon! is text. Without them, Python would look for an instruction called Hello and fail.
print shows the text without the quote marks and then moves to a new line. The output is Hello, Leon!
Try it: press Edit code, change Leon to your own name and press Run. Then add a second line, print("It works!"), and run again. The lines appear in the order you wrote them.
Common mistakes
Wrong
Print("Hello")
Python treats capital and small letters as different letters. It knows print and does not know Print. The error says: NameError: name 'Print' is not defined. Did you mean: 'print'? Python even suggests the fix.
Right
print("Hello")
Wrong
print("Hello)
The closing quote is missing, so Python cannot tell where the text ends. The error says: SyntaxError: unterminated string literal (detected at line 1). Every opening quote needs a closing quote of the same kind, and every opening bracket needs a closing bracket.
Right
print("Hello")
Wrong
print(“Hello”)
These curly quotes often sneak in when code is copied from a word processor or a web page. Python accepts only straight quotes, " or '. The error says: SyntaxError: invalid character '“' (U+201C).
Right
print("Hello")
Wrong
print "Hello"
Old tutorials written for Python 2 use print without brackets. In Python 3 the brackets are required. The error says: SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
Right
print("Hello")
Check yourself
Change the program so that it greets Mia instead of Leon. Write the whole line.
Try it first, then show the answer
print("Hello, Mia!") Only the words between the quote marks changed.
Write a two-line program that shows Start on the first line and Finish on the second. What does the output become if you swap the two lines?
Try it first, then show the answer
print("Start") print("Finish") After swapping, Finish appears first and Start second, because Python follows the lines from top to bottom.
02
Values, names and print
Goal store numbers under names, do arithmetic with them and show the results.
A value is one piece of information, such as the number 12 or the word Mia. Python has different kinds of value. A whole number such as 12 is an integer. A number with a decimal point such as 2.5 is a float. Text is a string. You wrote one in lesson 1, between quote marks.
A variable is a name that you attach to a value, so that you can use the value later. You make one with the equals sign. The line price = 4 means: take the value 4 and give it the name price. In maths, = says that two sides are equal. In Python it is an instruction to store. Python works out the right side first and then stores the result under the name on the left. A name may contain letters, digits and underscores. It cannot start with a digit and it cannot contain spaces. Choose names that say what the value is.
After that, you can use the name wherever you could use the value. The line total = price * 3 works out 4 times 3 and stores 12 under the name total. The arithmetic symbols are + to add, - to subtract, * to multiply and / to divide. Round brackets control the order, as in school maths. A division with / always gives a float, so 10 / 4 is 2.5 and 10 / 2 is 5.0.
Be careful: a variable holds a value, not a rule. If total was worked out from count, and you change count later, total keeps its old value until you work it out again. The example shows this.
print can show several things at once. Put commas between them, and print writes a space between the pieces. A line that starts with # is a comment. Python ignores it. It is a note for the people who read the code.
New words
value
One piece of information, such as 12 or "Mia".
integer
A whole number such as 12 or -3.
float
A number with a decimal point, such as 2.5.
string
Text in a program, written between quote marks.
variable
A name attached to a value.
assignment
Storing a value under a name with =.
comment
A note that starts with # and is ignored by Python.
Worked example
Python 3
# total cost of the notebooksprice=4count=3total=price*countprint("Total:",total)count=5print("Still:",total)total=price*countprint("Now:",total)
Predict the output first, then show it
Expected output
Total: 12
Still: 12
Now: 20
Step by step
The first line is a comment. It says what the code is for, and Python skips it.
price = 4 stores the integer 4 under the name price. count = 3 does the same for count.
In total = price * count, Python works out the right side first. price is 4 and count is 3, so the result is 12. Python stores 12 under the name total.
print("Total:", total) shows the text Total:, then a space, then the value 12.
count = 5 gives count a new value. The old value 3 is gone. But total was worked out earlier, so it is still 12. The line print("Still:", total) proves it.
total = price * count works out the right side again, 4 times 5, and stores 20. print shows Now: 20.
Try it: press Edit code, change price to 2.5 and run. The totals become floats: 7.5, 7.5 and 12.5.
Common mistakes
Wrong
12 = price
The name goes on the left and the value on the right. A number cannot be used as a name. The error says: SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
Right
price = 12
Wrong
print(total)
total = 5
Python runs lines from top to bottom. At the first line, total does not exist yet. The error says: NameError: name 'total' is not defined. Create a name before you use it.
Right
total = 5
print(total)
Wrong
my score = 5
A name cannot contain a space. Python sees two names next to each other and cannot make sense of them. The error says: SyntaxError: invalid syntax. Join the words with an underscore.
This prints 12, not 20. No error appears, which makes the mistake harder to spot. total was worked out once and stays 12. Work it out again after you change count.
Right
price = 4
count = 3
total = price * count
count = 5
total = price * count
print(total)
Check yourself
Predict what this program prints:
a = 2
b = a + 3
a = 10
print(b)
Try it first, then show the answer
5. b was worked out when a was 2, so b is 5. Changing a to 10 afterwards does not change b.
Write three lines: store 9 under the name apples, store 4 under the name oranges, and print how many fruits there are in total.
Try it first, then show the answer
apples = 9 oranges = 4 print("Fruit:", apples + oranges) It prints Fruit: 13.
Predict the output of print(7 / 2) and of print(8 / 2).
Try it first, then show the answer
3.5 and 4.0. Division with / always gives a float, even when the answer is a whole number.
03
Text: joining, measuring and changing
Goal join pieces of text, count its characters, change its case and put values inside text.
A string is text. You write it between quote marks, either "double" or 'single', as long as both ends match. A string can hold letters, digits, spaces and punctuation. The string "5" is text that looks like a number. It is not the number 5.
Join two strings with +. This is called concatenation. "Hello, " + "Mia" gives "Hello, Mia". The space is part of the first string, because Python adds no spaces for you. Strings and numbers do not mix with +. "Age: " + 5 is an error, because Python cannot tell whether you want to add or to join.
You have already used one function, print. A function is a named action that takes something in and, often, gives something back. Another function is len. It gives the number of characters in a string, spaces included. A method is an action that belongs to a value. You write the value, a dot, the method name and round brackets. "Mia".upper() gives "MIA". The method name must be spelled exactly, in small letters. A method never changes the original string. It gives back a new one.
A tidy way to put values inside text is an f-string. Write the letter f directly before the opening quote. Put names, or small calculations, inside curly brackets { }. Python replaces each pair of brackets with its value. f"{name} has {len(name)} letters" turns into a sentence with the real name and the real count.
New words
concatenation
Joining strings end to end with +.
character
One letter, digit, space or punctuation mark in a string.
function
A named action that takes something in and often gives something back. print and len are functions.
method
An action that belongs to a value, written after a dot, such as "Mia".upper().
f-string
A string with an f before the opening quote. Values in { } are filled in.
Worked example
Python 3
name="Mia"greeting="Hello, "+name+"!"print(greeting)print(len(name))print(name.upper())print(f"{name} has {len(name)} letters.")
Predict the output first, then show it
Expected output
Hello, Mia!
3
MIA
Mia has 3 letters.
Step by step
name = "Mia" stores the string Mia under the name name.
"Hello, " + name + "!" joins three strings: Hello, then the value of name, then an exclamation mark. The result, Hello, Mia!, is stored under greeting. Nothing is shown yet. print(greeting) shows it.
len(name) counts the characters M, i and a. The answer is the number 3, which print shows without quote marks.
name.upper() is the value, a dot and the method name. It gives a new string, MIA. The variable name still holds Mia.
In the f-string, {name} is replaced by Mia and {len(name)} is replaced by 3. The result is one sentence.
Try it: change "Mia" to "Noah" and run. All four lines change: Hello, Noah!, 4, NOAH and Noah has 4 letters.
Common mistakes
Wrong
age = 5
print("Age: " + age)
The + sign cannot join text and a number. The error says: TypeError: can only concatenate str (not "int") to str. Here str means string and int means integer. Put the number inside an f-string, or turn it into text with str(age) and write "Age: " + str(age).
Right
age = 5
print(f"Age: {age}")
Wrong
print(Hello)
Without quote marks, Python looks for a variable called Hello. The error says: NameError: name 'Hello' is not defined. Text needs quote marks. Names do not.
Right
print("Hello")
Wrong
print("5" + "5")
Both sides are text, so + joins them. This prints 55, not 10, and no error warns you. If you want to add, use numbers: 5 + 5.
Right
print(5 + 5)
Wrong
name = "Mia"
print(name.Upper())
Method names must be spelled exactly, and a capital U is a different letter. The error says: AttributeError: 'str' object has no attribute 'Upper'. Did you mean: 'upper'?
Right
name = "Mia"
print(name.upper())
Check yourself
Predict the output of print(len("Hello, Mia")).
Try it first, then show the answer
10. The string has Hello (5 characters), a comma, a space and Mia (3 characters): 5 + 1 + 1 + 3 = 10.
Write a program that stores "Noah" under the name name and prints NOAH has 4 letters. Build the sentence with an f-string.
Try it first, then show the answer
name = "Noah" print(f"{name.upper()} has {len(name)} letters.") Anything you could put inside print( ) also works inside the curly brackets.
04
Decisions with if
Goal make a program choose between actions.
Programs often need to choose. A school app shows a pass or a fail message depending on a mark. A choice starts with a question that has a yes-or-no answer. Python writes the question as a comparison. score >= 80 asks: is score at least 80? The answer is a value called True or False. A value like that is a boolean.
The comparison symbols are: == equal to, != not equal to, < less than, > greater than, <= less than or equal to, and >= greater than or equal to. Take care with ==. One equals sign stores a value. Two equals signs ask a question.
The if statement uses a comparison. Write the word if, then the comparison, then a colon. Below it, write the lines to run, moved four spaces to the right. Moving lines to the right is called indentation. Python uses indentation to know which lines belong to the if. The indented lines run only when the comparison is True. A line that goes back to the left edge is no longer part of the if, and it always runs.
Add else: to say what to do when the answer is False. Add elif (short for else if) to ask a second question when the first answer was False. Python checks the questions from the top, runs the lines under the first True one, and skips the rest. So the order of the questions matters.
New words
comparison
A question such as score >= 80 whose answer is True or False.
boolean
A value that is either True or False.
condition
The comparison written after if or elif.
indentation
Spaces at the start of a line. Python uses them to group lines.
if score >= 80: asks whether 72 is at least 80. The answer is False, so Python skips the indented line under it.
elif score >= 60: asks whether 72 is at least 60. The answer is True, so Python runs the indented line under it and prints Grade: B.
Python now skips the else part, because an earlier question was True. Only one of the three branches runs.
print("Done") is not indented. It is not part of the if chain, so it runs every time.
Try it: change score to 95, then to 40, then to 80. You should see Grade: A, then Grade: C, then Grade: A, because >= includes the number 80 itself.
Common mistakes
Wrong
score = 80
if score = 80:
print("Exactly 80")
One equals sign stores a value. To ask whether two things are equal, use two. The error says: SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
Right
score = 80
if score == 80:
print("Exactly 80")
Wrong
score = 80
if score >= 80
print("A")
The colon at the end of the if line is missing. The error says: SyntaxError: expected ':'. Lines that introduce an indented block, such as if, elif, else, for, while and def, all end with a colon.
Right
score = 80
if score >= 80:
print("A")
Wrong
score = 80
if score >= 80:
print("A")
The line under the if is not indented, so Python finds an if with nothing inside it. The error says: IndentationError: expected an indented block after 'if' statement on line 2. Indent the line by four spaces.
There is no error, but 90 prints Grade: B. The first question, at least 60, is already True, so Python never reaches the second one. Put the strictest question first.
Grade: A and then Done. The comparison score >= 80 is True when score is exactly 80.
Predict the output:
x = 5
if x > 3:
print("A")
if x > 4:
print("B")
else:
print("C")
Try it first, then show the answer
A, then B on the next line. These are two separate if statements. The first prints A. The second asks whether 5 is greater than 4, which is True, so it prints B and skips its else.
Write a program: age is 16. Print Adult if age is 18 or more, and Minor otherwise.
Try it first, then show the answer
age = 16 if age >= 18: print("Adult") else: print("Minor") It prints Minor.
05
Repeating with for and while
Goal repeat steps with a for loop and a while loop, and know which to pick.
A loop repeats lines of code. Without loops, a program that adds up 100 numbers would need 100 lines. Python has two kinds of loop.
A for loop repeats once for each item in a group of values. The simplest group comes from range. range(1, 6) gives the whole numbers 1, 2, 3, 4 and 5. It starts at the first number and stops before the second one. range(3) is short for range(0, 3) and gives 0, 1 and 2. You write for number in range(1, 6): and then the lines to repeat, indented by four spaces. Each time round, number holds the next value. One pass through the indented lines is called an iteration.
A while loop repeats as long as a comparison stays True. Python checks the comparison before every pass. Something inside the loop must change what the comparison sees. Otherwise it stays True forever, which is called an infinite loop, and the program never stops. In a terminal, press Control and C to stop it. On this page, do not run a loop that never ends. Reload the page if that happens.
Use for when you know what to go through, or how many times. Use while when you repeat until something happens. A common pattern is a running total: start a variable at 0, and add to it inside the loop.
New words
loop
Code that repeats.
iteration
One pass through the lines of a loop.
range
A way to get a run of whole numbers. It stops before the end number.
infinite loop
A loop whose comparison never becomes False, so it never stops.
added 1 total is 1
added 2 total is 3
added 3 total is 6
added 4 total is 10
added 5 total is 15
Sum: 15
Countdown: 3
Countdown: 2
Countdown: 1
Liftoff
Step by step
total = 0 starts a running total at zero.
for number in range(1, 6): makes number take the values 1, 2, 3, 4 and 5, one after another. range(1, 6) stops before 6.
The two indented lines run five times. Each time, total = total + number adds the current number to the total, and print shows the progress.
print("Sum:", total) is not indented. It runs once, after the loop has finished.
The while loop starts with count = 3. Python asks count > 0 before each pass. It is True for 3, 2 and 1.
count = count - 1 is the line that changes count. After the pass where count is 1, count becomes 0, the question is False, and the loop ends. Then Liftoff is printed.
Try it: change range(1, 6) to range(1, 11) and the last Sum becomes 55. Change count = 3 to count = 5 and the countdown gets longer.
Common mistakes
Wrong
for n in range(5):
print(n)
This prints 0, 1, 2, 3 and 4. That is five numbers, but they start at 0 and stop before 5. There is no error, so check the output. For 1 to 5, write range(1, 6).
Right
for n in range(1, 6):
print(n)
Wrong
count = 3
while count > 0:
print(count)
count never changes, so count > 0 stays True and the program prints 3 forever. Stop it with Control and C in a terminal. Change the variable inside the loop.
A for loop needs a group of values to go through, and a single number is not one. The error says: TypeError: 'int' object is not iterable. Use range(5) to go through the numbers 0 to 4.
Right
for i in range(5):
print(i)
Wrong
total = 0
for n in range(1, 4):
total = total + n
print("running total", total)
Suppose you wanted to see the total after every step. The print is lined up with for, so it is not part of the loop. It runs once at the end and shows only 6. Indentation decides what repeats.
Right
total = 0
for n in range(1, 4):
total = total + n
print("running total", total)
Check yourself
Predict the output:
for i in range(3):
print(i * 2)
Try it first, then show the answer
0, 2 and 4, each on its own line. i takes the values 0, 1 and 2.
Write a loop that prints 10, 20, 30, 40 and 50, each on its own line.
Try it first, then show the answer
for n in range(1, 6): print(n * 10) Another answer with the same output is range(10, 51, 10), but you have not met that form yet.
Predict the output:
count = 1
while count < 4:
print(count)
count = count + 1
Try it first, then show the answer
1, 2 and 3, each on its own line. When count reaches 4, the question count < 4 is False and the loop ends.
06
Lists
Goal keep several values together, read one by its position and go through all of them.
A list keeps many values in order under one name. Write the values between square brackets, separated by commas: scores = [70, 85, 90]. A list can hold numbers, strings or a mix. The function len tells you how many items a list holds.
Each item has a position, called an index. Counting starts at 0, not 1. In scores, the item at index 0 is 70, at index 1 is 85 and at index 2 is 90. Write scores[0] to get the first item. A negative index counts from the end, so scores[-1] is the last item. If you ask for a position that does not exist, Python stops with an IndexError. Strings use the same idea: "Mia"[0] is "M".
A list can change. The method append adds one item at the end. scores.append(60) changes scores itself. It gives nothing back.
A for loop can go through a list item by item: for score in scores: is the same for loop as in lesson 5, with a list in place of range. With a list you can total and average a set of marks, which is what the example does.
New words
list
Many values kept in order under one name, written in square brackets.
item
One value inside a list.
index
The position of an item. The first item has index 0.
scores = [70, 85, 90] makes a list of three integers.
scores[0] is the item at index 0, the first one: 70.
scores[-1] counts from the end, so it is the last item: 90.
scores.append(60) adds 60 at the end. The list is now [70, 85, 90, 60].
len(scores) is now 4.
The loop gives score the values 70, 85, 90 and 60 in turn. total grows to 70 + 85 + 90 + 60 = 305.
total / len(scores) is 305 / 4 = 76.25, the average.
Try it: add scores.append(100) after the first append and run. There are now five scores, the total is 405, and the last line shows Average: 81.0.
Common mistakes
Wrong
scores = [70, 85, 90]
print(scores[3])
The list has three items, with indexes 0, 1 and 2. There is no index 3. The error says: IndexError: list index out of range. The last valid index is len(scores) - 1, which you can also write as -1.
Right
scores = [70, 85, 90]
print(scores[2])
Wrong
scores = [70, 85, 90]
print(scores[1])
If you wanted the first score, this is wrong, and no error tells you. scores[1] is the second item, 85. The first item has index 0.
append changes the list and gives back nothing, which Python calls None. Storing that result under scores throws the list away. The error says: TypeError: object of type 'NoneType' has no len(). Call append on a line of its own.
Round brackets call a function. Square brackets pick an item. The error says: TypeError: 'list' object is not callable.
Right
scores = [70, 85, 90]
print(scores[0])
Check yourself
Predict the output:
names = ["Leon", "Mia", "Emma"]
print(names[1])
print(names[-1])
Try it first, then show the answer
Mia and then Emma. Index 1 is the second item, and -1 is the last item.
Using the list names above, write a loop that prints Hello, Leon then Hello, Mia then Hello, Emma.
Try it first, then show the answer
for name in names: print("Hello, " + name)
A list has 6 items. What is the largest valid index?
Try it first, then show the answer
5, because counting starts at 0. You can also reach the last item with -1.
07
Functions
Goal write a function that takes inputs and returns a result, and then call it.
You have used functions already: print, len and range. A function is a named set of steps that you can use again and again. You can write your own.
Write def, then the name, then round brackets holding the parameters, then a colon. A parameter is a name for an input. The function uses it like a variable. The steps of the function are indented below. The word return sends a result back to the code that used the function. That result is the return value.
Defining a function does not run it. The def line only teaches Python a new name. To run it, call the function: write its name and give it values in round brackets, such as average(class_a). The values you give are called arguments. Each argument is stored in the matching parameter, in order.
Names created inside a function exist only while it runs. They are local. That protects you: a function cannot accidentally change variables elsewhere in the program.
return and print are different. print shows something on the screen for a person. return hands a value back to the program, so that it can be stored, added or printed. If a function finishes without return, it gives back None, which means no value. A return also ends the function at once.
New words
function
A named set of steps you can use again and again.
parameter
A name for an input, written in the brackets of def.
argument
The actual value you give when you call a function.
call
Running a function by writing its name and brackets.
def average(numbers): defines a function called average with one parameter, numbers. Nothing runs yet.
The indented lines are the body of the function. It is the loop from lesson 6, with numbers in place of scores.
return total / len(numbers) sends the average back and ends the function.
def percent(part, whole): has two parameters. They receive their values in order.
class_a and class_b are two lists. They are ordinary variables.
average(class_a) calls the function. Python stores the list in numbers, runs the body and gets 76.25. The call is replaced by that return value, and print shows it.
average(class_b) uses the same steps on different data. Reusing steps is the point of a function. It gives 75.0.
percent(3, 4) stores 3 in part and 4 in whole. The result is 3 / 4 * 100 = 75.0.
Try it: add class_c = [100, 90, 80] and print(average(class_c)). You should see 90.0.
Common mistakes
Wrong
def greet(name):
print("Hello, " + name)
Nothing prints and no error appears. def only defines the function, and nobody calls it. Add a line that calls it, such as greet("Mia").
print only shows the result. It does not hand it back, so square(4) is None. The program prints 16 and then stops with: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'. Use return.
Right
def square(x):
return x * x
y = square(4) + 1
Wrong
def square(x):
return x * x
print(square(2, 3))
The function has one parameter, but the call gives two arguments. The error says: TypeError: square() takes 1 positional argument but 2 were given. The number of arguments must match the number of parameters.
Right
def square(x):
return x * x
print(square(2))
Wrong
def total_of(numbers):
total = 0
for n in numbers:
total = total + n
return total
return ends the function at once. Here it sits inside the loop, so the loop stops after the first item, and total_of([1, 2, 3]) gives 1 instead of 6. There is no error. Line return up with for so that it runs after the loop.
Right
def total_of(numbers):
total = 0
for n in numbers:
total = total + n
return total
Check yourself
Write a function double that takes a number n and returns twice n. Then print double(21).
Try it first, then show the answer
def double(n): return n * 2
print(double(21)) It prints 42.
Predict the output:
def f(a, b):
return a - b
print(f(10, 4))
print(f(4, 10))
Try it first, then show the answer
6 and then -6. Arguments go into the parameters in order, so the order of the arguments changes the answer.
Predict the output:
def hello():
print("Hi")
x = hello()
print(x)
Try it first, then show the answer
Hi and then None. The call prints Hi. The function has no return, so x gets None.
08
Reading an error message and fixing it
Goal find the kind, the place and the cause of an error, and fix a broken program one message at a time.
Every programmer sees error messages every day. They are not a sign that you failed. An error message is Python telling you where it stopped and why. The skill is to read it calmly, in the right order.
A mistake found while the program runs gives a message of this shape: Traceback (most recent call last): File "hello.py", line 4, in <module> total = totl + price NameError: name 'totl' is not defined. Did you mean: 'total'?
Read it from the bottom. The last line is the most useful. It has the kind of error (here NameError), a colon, and a sentence about what went wrong. Just above it is the line of your program where Python stopped. Above that are the file name and the line number. On this page the file is called main.py. Traceback means the trail of steps Python took to get there; in a short program the trail has one step. Newer versions of Python also print ^ marks under the exact part of the line, and the wording of messages differs a little between versions.
A mistake in the way a line is written is a syntax error. Python finds these before it runs anything. So the message has no Traceback, and the program prints nothing at all. Python shows the line and a ^ mark near the problem. The real mistake is at that spot or just before it.
Do the same four things every time. First, read the last line aloud. Second, go to the line number it names. Third, change one thing. Fourth, run again. Python stops at the first error, so fixing one often shows you the next. That is progress.
New words
SyntaxError
A line is written in a way Python cannot understand. Nothing runs.
IndentationError
A kind of SyntaxError: the spaces at the start of a line are wrong.
NameError
A name does not exist. Often a typo, or a variable not created yet.
TypeError
An action was used on the wrong kind of value, such as text plus a number.
IndexError
A list position that does not exist.
ZeroDivisionError
A division by zero.
traceback
The trail of steps Python shows when a program stops with an error.
This is the repaired program. Mia's first version had three mistakes, and Python reported them one at a time. You can bring each one back and read the message yourself: press Edit code, make the change, press Run, and read the box under the code. Put the code back each time, or press Reset.
Mistake 1: delete the colon at the end of line 3, so it reads for price in prices. Run it. The message ends with SyntaxError: expected ':' and names line 3. It is a syntax error, so nothing ran and nothing was printed.
Mistake 2: on line 4, change total + price to totl + price. Run it. The message ends with NameError: name 'totl' is not defined. Did you mean: 'total'? and names line 4. Python has never seen the name totl, and it guesses that you meant total.
Mistake 3: on line 6, change print("Total:", total) to print("Total: " + total). Run it. The message ends with TypeError: can only concatenate str (not "int") to str and names line 6. The + sign cannot join text and a number. This error appears only after lines 1 to 5 have run.
With all three fixed, you get the output above: Total: 15 and Average: 5.0. Each message told you the line and the cause. Reading the last line first is what made the fixes quick.
Common mistakes
Wrong
count = 0
print(10 / count)
Dividing by zero has no answer. The error says: ZeroDivisionError: division by zero. The cause is often a value that you expected to be above 0, such as the length of an empty list. Check before you divide.
Right
count = 0
if count > 0:
print(10 / count)
else:
print("Nothing to divide")
Wrong
print("Total:", (4 + 5)
print("Done")
A bracket is never closed. The error says: SyntaxError: '(' was never closed, and the ^ mark points at the bracket that is still open. Older versions of Python complain about the next line instead, which is why the real mistake can be just before the place Python points to.
Right
print("Total:", (4 + 5))
print("Done")
Wrong
print("a")
print("b")
The second line starts with four spaces that nothing asked for. The error says: IndentationError: unexpected indent. Only a line after a colon should be indented. Delete the spaces.
Right
print("a")
print("b")
Check yourself
A program stops, and the last line of the message is: NameError: name 'nmae' is not defined. Did you mean: 'name'? The line above it is print(nmae). Write the corrected line.
Try it first, then show the answer
print(name). The name was misspelled, and Python's guess is right.
The line print("Score: " + 90) fails. Name the kind of error and write two different ways to fix it.
Try it first, then show the answer
It is a TypeError, because + cannot join text and a number. Fixes: print("Score:", 90) or print(f"Score: {90}") or print("Score: " + str(90)).
A file has a missing colon on line 5 and a misspelled name on line 2. Line 1 is print("Start"). Which error appears, and does Start get printed?
Try it first, then show the answer
The SyntaxError about the colon appears, and Start is not printed. Python checks how the whole file is written before it runs any line. The misspelled name is a NameError, which can only appear while the program runs.