Free Python course

Six short topics that take you from your first line of code to writing your own function. Everything runs in the box on this page, in your own browser. There is no account to make, nothing to install and no fee.

This is a free course and not a qualification. It carries no certificate and no accreditation. If you want a regulated qualification afterwards, our data and analytics courses lead to one.

Practice box

Python loads when you press Run. It is about 6 MB, once.

or press Ctrl and Enter

The examples all come from one small business. Mill Lane Bakery sells four things, and Ama runs the counter. You will count her loaves, work out her takings and print her a summary.

  1. What Python is, and your first line
  2. Variables and the four basic types
  3. Working with text
  4. Lists, and doing something to each item
  5. Making decisions
  6. Functions, and reading an error

1 What Python is, and your first line

Python is a language for giving a computer instructions.

You write the instructions, and the computer follows them in order.

In this topic you run your first line of code.

You also learn how to show a result on the screen.

Words to know

Python
A programming language used to give a computer instructions.
Code
The instructions you write for the computer.
Program
A set of instructions saved together and run as one.
Run
To make the computer carry out your code.
Output
What your code shows on the screen after it runs.
print
An instruction that shows a value on the screen.
String
A piece of text, written inside quote marks.
Error
A message telling you the computer could not follow a line.

By the end of this topic you can

  • say what Python is (1.1)
  • run a line of code (1.2)
  • use print to show a value (1.3)
  • tell code apart from output (1.4)

What Python is

What it means. Python is a language for giving a computer instructions.

A computer does nothing on its own.

You tell it what to do, one line at a time.

Python is one of the clearest languages for doing that.

People use Python for

  • counting and adding up figures
  • sorting and tidying lists of data
  • reading and writing files
  • drawing charts
  • building websites

The same four ideas cover all of those uses.

You will meet all four in this course.

print("Mill Lane Bakery")

It shows

Mill Lane Bakery

Example

Ama wants the shop name on her daily sheet.

One line of Python prints it.

The computer shows the text and stops.

Check: What does Python do for you?

It lets you give the computer instructions it can follow.

Showing something with print

What it means. print is an instruction that shows a value on the screen.

You write print, then round brackets.

Inside the brackets you put what you want shown.

Text goes inside quote marks.

A print line has three parts

  • the word print
  • a pair of round brackets
  • the value you want to see

Miss a bracket and Python stops.

It tells you which line it could not read.

print("Open at 7am")
print("Four things on sale today")

It shows

Open at 7am
Four things on sale today

Example

Ama prints two notes for the counter.

Each print puts its text on its own line.

The order on screen matches the order you wrote.

Check: How many lines will two print instructions show?

Two. Each print starts a new line.

Code and output are different things

What it means. Code is what you write. Output is what the computer shows back.

The box on this page has two parts.

You type code at the top.

The output appears underneath after you press Run.

Watch for these

  • code sits in the top box
  • output sits in the bottom box
  • quote marks are code, so they never appear in the output
  • an error replaces the output

The quote marks tell Python where the text starts and ends.

They are not part of the text itself.

print("3 + 4")
print(3 + 4)

It shows

3 + 4
7

Example

The first line prints the characters 3 + 4.

The second line adds the numbers first.

Quote marks are the only difference between them.

Check: Why does the first line show 3 + 4 and not 7?

The quote marks make it text, so Python shows it exactly.

Watch out

Every opening bracket needs a closing bracket. Python reads to the end of the line and then reports a syntax error.

Quote marks must match. Start with a double quote and end with a double quote.

Python cares about spelling. Write prnt instead of print and Python does not know the word.

What you have learned

  • Python is a language for giving a computer instructions (1.1)
  • you run code by pressing Run (1.2)
  • print shows a value on the screen (1.3)
  • code is what you write and output is what comes back (1.4)

2 Variables and the four basic types

A variable is a name that holds a value.

You put a value in it once and use the name afterwards.

In this topic you store numbers and text.

You also learn the four types a value can have.

Words to know

Variable
A name that holds a value you can use later.
Assign
To put a value into a variable, using one equals sign.
Value
The thing a variable holds, such as 12 or a name.
Type
What kind of thing a value is, such as text or a number.
Integer
A whole number, with no decimal point.
Float
A number with a decimal point.
Boolean
A value that is either True or False.
type()
An instruction that tells you the type of a value.

By the end of this topic you can

  • store a value in a variable (2.1)
  • name the four basic types (2.2)
  • check the type of a value (2.3)
  • change what a variable holds (2.4)

Putting a value in a variable

What it means. A variable is a name that holds a value you can use later.

You choose the name yourself.

One equals sign puts a value into it.

After that, the name stands for the value.

Rules for a variable name

  • use letters, numbers and the underscore
  • never start with a number
  • no spaces in the name
  • choose a name that says what it holds

A clear name saves you reading the whole program later.

Write loaves_sold rather than x.

loaves_sold = 12
print(loaves_sold)

It shows

12

Example

Ama sold 12 sourdough loaves on Monday.

She stores the figure under a clear name.

Printing the name shows the value it holds.

Check: What does one equals sign do?

It puts the value on the right into the name on the left.

The four basic types

What it means. A type is what kind of thing a value is.

Python treats text and numbers differently.

It needs to know which it has.

Most values you meet are one of four types.

The four types

  • string, which is text in quote marks
  • integer, which is a whole number
  • float, which is a number with a decimal point
  • boolean, which is True or False

A price needs a float, because it has pence.

A count of loaves needs an integer, because you cannot sell half a loaf.

A float is not always exact, so money sums sometimes need rounding.

item = "sourdough"
count = 12
price = 3.50
fresh = True
print(type(item))
print(type(count))
print(type(price))
print(type(fresh))

It shows

<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

Example

Ama records one sale four ways.

The item is text and the count is a whole number.

The price has pence, so it is a float.

Check: Which type would you use for a price?

A float, because a price has a decimal point.

Changing what a variable holds

What it means. You can put a new value into a variable at any time.

Assigning again replaces the old value.

The old value is gone.

Python keeps only what you put in last.

Common ways to change a value

  • assign a new value outright
  • add to the value and assign the result
  • use the shorter form with plus equals

The shorter form does the same job in fewer characters.

Both lines below leave the same number behind.

loaves_sold = 12
loaves_sold = loaves_sold + 5
print(loaves_sold)
loaves_sold += 4
print(loaves_sold)

It shows

17
21

Example

Ama sells 5 more loaves at lunch.

She adds them to the morning figure.

Four more go in the afternoon.

Check: What does plus equals do?

It adds to the value already in the variable and stores the result.

Watch out

One equals sign assigns and two compare. Writing count = 12 stores a value, and count == 12 asks a question.

A number in quote marks is text. Python treats "12" as a string, so it cannot be added to 5.

A variable must be assigned before it is used. Using a name Python has never seen gives a NameError.

What you have learned

  • a variable holds a value under a name you choose (2.1)
  • the four basic types are string, integer, float and boolean (2.2)
  • type() tells you what kind of value you have (2.3)
  • assigning again replaces what the variable held (2.4)

3 Working with text

Text in Python is called a string.

You can join strings, measure them and change their case.

In this topic you build a line of text from values.

You also tidy text that arrives untidy.

Words to know

String
A piece of text, written inside quote marks.
f-string
A string with an f in front, which can hold values inside it.
Method
An instruction that belongs to a value, written after a full stop.
upper()
A method that returns the text in capital letters.
lower()
A method that returns the text in small letters.
strip()
A method that removes spaces from both ends of the text.
len()
An instruction that gives the number of characters or items.
Concatenate
To join two strings end to end.

By the end of this topic you can

  • join two pieces of text (3.1)
  • put a value inside a sentence (3.2)
  • use a string method (3.3)
  • measure a piece of text (3.4)

Joining text

What it means. To concatenate is to join two strings end to end.

The plus sign joins two strings.

It does not add a space for you.

You put any space you want inside the quote marks.

What plus does

  • between two strings, it joins them
  • between two numbers, it adds them
  • between a string and a number, it fails

That last case is one of the most common beginner errors.

You will see the message for it in topic 6.

first = "Mill Lane"
second = "Bakery"
print(first + " " + second)

It shows

Mill Lane Bakery

Example

Ama holds the two halves of the shop name.

She joins them with a space between.

The space is a string of its own.

Check: Why is there a space in quote marks in the middle?

Because plus joins text exactly, and adds no space itself.

Putting a value inside a sentence

What it means. An f-string is a string that can hold values inside it.

Put the letter f before the opening quote.

Then put any value in curly brackets.

Python replaces the brackets with the value.

An f-string is useful because

  • you do not have to join pieces with plus
  • numbers go in without being turned into text first
  • the line reads like the sentence it produces

This is the normal way to build a sentence in modern Python.

Use it instead of plus whenever a value is involved.

item = "sourdough"
count = 12
print(f"Ama sold {count} {item} loaves.")

It shows

Ama sold 12 sourdough loaves.

Example

Ama wants one clear line for her daily sheet.

The count and the item drop into place.

She does not have to turn 12 into text first.

Check: What do the curly brackets do in an f-string?

They hold a value, which Python puts into the text.

Methods that change text

What it means. A method is an instruction that belongs to a value.

You write the value, a full stop, then the method.

The method gives back a new string.

It never changes the original.

Three methods you will use often

  • upper() gives the text in capital letters
  • lower() gives the text in small letters
  • strip() removes spaces from both ends

Text typed by people often has a stray space at the end.

strip() is how you tidy it before comparing it.

typed = "  Sourdough  "
print(f"[{typed.strip()}]")
print(typed.strip().lower())
print(typed.strip().upper())

It shows

[Sourdough]
sourdough
SOURDOUGH

Example

A delivery note arrives with spaces around the name.

strip() removes them from both ends.

The square brackets show where the text now ends.

Check: Does upper() change the original string?

No. It gives back a new string and leaves the original alone.

Measuring text

What it means. len() gives the number of characters in a string.

Write len, then the value in round brackets.

Spaces count as characters.

The answer is always a whole number.

len() works on

  • a string, giving the number of characters
  • a list, giving the number of items
  • anything else with a length

You will use len() on a list in the next topic.

It is the same instruction either way.

name = "Mill Lane Bakery"
print(len(name))
print(len("sourdough"))

It shows

16
9

Example

Ama checks the shop name fits her label.

The two spaces are counted as characters.

Sixteen characters is within her limit.

Check: Do spaces count towards the length?

Yes. Every character counts, including spaces.

Watch out

You cannot join a string to a number with plus. Use an f-string instead, which handles the number for you.

A method needs its round brackets. Writing name.upper without brackets does not run the method.

strip() only removes spaces at the ends. A space in the middle of the text stays where it is.

What you have learned

  • plus joins two strings end to end (3.1)
  • an f-string puts a value inside a sentence (3.2)
  • upper(), lower() and strip() give back a new string (3.3)
  • len() counts the characters in a string (3.4)

4 Lists, and doing something to each item

A list holds several values in order under one name.

You can read any item, add to the list and count it.

In this topic you store a day of sales in one list.

You also run the same instruction on every item.

Words to know

List
A set of values kept in order under one name.
Item
One value inside a list.
Index
The position of an item, counted from zero.
append()
A method that adds one item to the end of a list.
Loop
An instruction that repeats for each item in turn.
for
The word that starts a loop.
Indent
The spaces at the start of a line, which show what belongs to the loop.
sum()
An instruction that adds up all the numbers in a list.

By the end of this topic you can

  • make a list (4.1)
  • read an item by its position (4.2)
  • add an item to a list (4.3)
  • do something to every item (4.4)

Making a list

What it means. A list is a set of values kept in order under one name.

Square brackets hold the items.

Commas separate them.

The items stay in the order you wrote them.

A list can hold

  • numbers
  • strings
  • True and False values
  • a mixture of those

Keep one kind of thing in a list where you can.

A list of counts is easier to add up than a mixture.

sales = [12, 5, 9, 7]
print(sales)
print(len(sales))
print(sum(sales))

It shows

[12, 5, 9, 7]
4
33

Example

Ama sold four kinds of thing on Monday.

One list holds all four counts.

len() counts the items and sum() adds them up.

Check: What does len() give you for a list?

The number of items in it.

Reading one item

What it means. An index is the position of an item, counted from zero.

The first item is at index 0.

The second is at index 1.

Square brackets after the name read one item.

Counting from zero

  • index 0 is the first item
  • index 1 is the second item
  • index -1 is the last item
  • an index past the end gives an error

Counting from zero catches everybody out at first.

A list of four items has indexes 0 to 3.

items = ["sourdough", "white tin", "seeded roll", "fruit scone"]
print(items[0])
print(items[2])
print(items[-1])

It shows

sourdough
seeded roll
fruit scone

Example

Ama lists the four things she sells.

The first is at position zero, not one.

Minus one reaches the last without counting.

Check: Which index holds the first item?

Index 0.

Adding to a list

What it means. append() adds one item to the end of a list.

Write the list name, a full stop, then append.

Put the new item in the brackets.

The list grows by one.

append() in use

  • it always adds to the end
  • it adds one item at a time
  • it changes the list itself
  • it gives nothing back

This is different from the string methods in topic 3.

Those gave back a new value and left the original alone.

items = ["sourdough", "white tin"]
items.append("seeded roll")
print(items)
print(len(items))

It shows

['sourdough', 'white tin', 'seeded roll']
3

Example

Ama starts the week with two lines.

A third goes on the board at midday.

The list now holds three.

Check: Where does append() put the new item?

At the end of the list.

Doing something to every item

What it means. A loop repeats an instruction for each item in turn.

Write for, a name for one item, then in and the list.

End the line with a colon.

Indent the lines that belong to the loop.

A for loop has four parts

  • the word for
  • a name for the current item
  • the word in and the list
  • a colon, then indented lines

The indent is how Python knows what to repeat.

Four spaces is the normal amount.

items = ["sourdough", "white tin", "seeded roll"]
for item in items:
    print(f"Check stock of {item}")

It shows

Check stock of sourdough
Check stock of white tin
Check stock of seeded roll

Example

Ama wants a stock line for each thing she sells.

The loop writes one line per item.

She does not repeat the print herself.

Check: What tells Python which lines belong to the loop?

The indent at the start of those lines.

Watch out

A list of four items has no index 4. The indexes run from 0 to 3, so index 4 gives an IndexError.

The for line must end with a colon. Leave it off and Python reports a syntax error on that line.

The lines inside the loop must be indented. Without the indent Python does not know what to repeat.

What you have learned

  • a list holds several values in order (4.1)
  • an index reads one item, counting from zero (4.2)
  • append() adds an item to the end (4.3)
  • a for loop does the same thing to every item (4.4)

5 Making decisions

Code can take one path or another.

You ask a question, and Python runs the lines that fit the answer.

In this topic you compare values.

You also put a decision inside a loop.

Words to know

Condition
A question that is either True or False.
if
The word that starts a decision.
else
The word for what to do when the condition is False.
elif
Short for else if, used to ask a second question.
Comparison
A test such as greater than or equal to.
==
Two equals signs, which ask whether two values are the same.
and
A word that joins two conditions, needing both to be True.
or
A word that joins two conditions, needing only one to be True.

By the end of this topic you can

  • compare two values (5.1)
  • write an if statement (5.2)
  • add elif and else (5.3)
  • put a decision inside a loop (5.4)

Comparing two values

What it means. A condition is a question that is either True or False.

A comparison asks about two values.

The answer is always True or False.

Those are the boolean values from topic 2.

The comparisons you need

  • == asks whether two values are the same
  • != asks whether they are different
  • > and < ask which is larger
  • >= and <= allow the two to be equal

Two equals signs ask a question.

One equals sign stores a value instead.

sold = 12
print(sold > 10)
print(sold == 12)
print(sold != 12)

It shows

True
True
False

Example

Ama checks whether she beat ten loaves.

The answer comes back as True.

She has not changed the figure by asking.

Check: What is the difference between = and ==?

One equals sign stores a value. Two ask whether values are the same.

Taking one path or another

What it means. if runs a block of lines only when a condition is True.

Write if, then the condition, then a colon.

Indent the lines that should run.

Add else for what to do otherwise.

How Python reads it

  • it works out the condition first
  • if the answer is True it runs the indented lines
  • if the answer is False it runs the else lines
  • it never runs both

The shape is the same as the loop in topic 4.

A colon, then an indent, marks the lines that belong.

sold = 12
if sold > 10:
    print("Good morning for sourdough")
else:
    print("Quiet morning")

It shows

Good morning for sourdough

Example

Ama calls anything over ten a good morning.

Twelve is over ten, so the first line prints.

The else line is skipped entirely.

Check: Can both the if lines and the else lines run?

No. Python runs one or the other, never both.

Asking a second question

What it means. elif asks another question when the one before it was False.

elif is short for else if.

You can use as many as you need.

Python stops at the first one that is True.

The order matters

  • Python checks the if first
  • then each elif in the order you wrote them
  • it runs the first block that fits
  • else catches everything left over

Put the narrowest test first.

A wide test at the top catches cases you meant for a later line.

sold = 7
if sold > 10:
    print("Busy")
elif sold > 5:
    print("Steady")
else:
    print("Quiet")

It shows

Steady

Example

Ama grades her morning in three bands.

Seven is not over ten but it is over five.

The steady line prints and the rest are skipped.

Check: Why does Python not print Quiet as well?

It stops at the first condition that is True.

A decision inside a loop

What it means. You can put an if inside a for loop to test every item.

The loop takes each item in turn.

The if then asks about that item.

Lines inside both are indented twice.

Reading the indents

  • four spaces means inside the loop
  • eight spaces means inside the if as well
  • no indent means outside both

This pattern finds the items that matter.

It is the most common shape in everyday Python.

sales = [12, 5, 9, 7]
items = ["sourdough", "white tin", "seeded roll", "fruit scone"]
for i in range(len(sales)):
    if sales[i] > 8:
        print(f"{items[i]} sold well at {sales[i]}")

It shows

sourdough sold well at 12
seeded roll sold well at 9

Example

Ama wants only the lines that sold more than eight.

The loop looks at each of the four in turn.

Two of them pass the test.

Check: How many spaces does the print line need here?

Eight, because it sits inside the loop and inside the if.

Watch out

Use two equals signs to compare. One equals sign inside an if is a syntax error.

elif only runs when the lines above it were False. If the first condition is True, Python never looks at the rest.

Every if line ends with a colon. So does every elif and every else.

What you have learned

  • a comparison gives back True or False (5.1)
  • if runs lines only when a condition is True (5.2)
  • elif and else cover the other cases (5.3)
  • an if inside a loop tests every item (5.4)

6 Functions, and reading an error

A function is a piece of code you name and reuse.

You write it once and call it as often as you like.

In this topic you write your own function.

You also learn to read the error messages Python gives you.

Words to know

Function
A named piece of code you can run whenever you need it.
def
The word that starts a function.
Parameter
A name in the brackets, standing for a value passed in.
Argument
The actual value you pass to a function when you call it.
return
The word that sends a value back from a function.
Call
To run a function by writing its name and brackets.
NameError
The error Python gives when it does not know a name.
TypeError
The error Python gives when a value is the wrong type.

By the end of this topic you can

  • write a function (6.1)
  • pass a value into a function (6.2)
  • send a value back with return (6.3)
  • read an error and fix it (6.4)

Writing a function

What it means. A function is a named piece of code you can run whenever you need it.

Write def, the name, then round brackets and a colon.

Indent the lines inside.

Nothing runs until you call it.

Why functions are worth it

  • you write the steps once
  • you give them a name that says what they do
  • a fix in one place fixes every use
  • the rest of your code gets shorter

Defining a function and calling it are two separate things.

A function you never call does nothing at all.

def greet():
    print("Welcome to Mill Lane Bakery")

greet()
greet()

It shows

Welcome to Mill Lane Bakery
Welcome to Mill Lane Bakery

Example

Ama greets every customer the same way.

The words live in one place.

Calling it twice prints it twice.

Check: What happens if you define a function but never call it?

Nothing. The lines inside it do not run.

Passing a value in

What it means. A parameter is a name in the brackets, standing for a value passed in.

Put a name inside the brackets when you define it.

Pass a value when you call it.

Inside the function, the name holds that value.

Two words that are easy to mix up

  • a parameter is the name in the definition
  • an argument is the value you pass in
  • they meet when the function runs

One function can then serve many cases.

You change the value, not the function.

def greet(name):
    print(f"Good morning, {name}")

greet("Ama")
greet("Joe")

It shows

Good morning, Ama
Good morning, Joe

Example

Ama greets staff by name.

The function holds the wording.

The name changes with each call.

Check: What is the difference between a parameter and an argument?

A parameter is the name in the definition. An argument is the value you pass.

Sending a value back

What it means. return sends a value out of a function to whatever called it.

print shows a value on the screen.

return hands it back to your code.

You can then store it or use it in a sum.

print and return are not the same

  • print puts text on the screen and gives nothing back
  • return gives a value back and shows nothing
  • a function stops the moment it returns

Use return when the answer is needed later.

Use print when a person needs to read it now.

def takings(count, price):
    return count * price

morning = takings(12, 3.50)
print(morning)
print(takings(5, 2.50) + takings(9, 0.75))

It shows

42.0
19.25

Example

Ama works out takings for a line of sales.

The function gives back a number, so she can add two of them.

The answer shows as 42.0, because a float keeps its decimal point.

Check: Why use return rather than print here?

Because the value is needed for another sum afterwards.

Reading an error

What it means. An error message names the problem and the line it happened on.

Python stops at the first line it cannot run.

It then tells you what went wrong.

Read the last line of the message first.

The errors you will meet most

  • NameError, when Python does not know a name
  • TypeError, when a value is the wrong type
  • IndexError, when a position is past the end of a list
  • SyntaxError, when a line cannot be read at all

Python often suggests the word you meant.

Fix the first error and run it again, because the rest may go with it.

price = 3.50
print("The price is " + price)

This stops with an error

TypeError on line 2: can only concatenate str (not "float") to str

Example

Ama tries to join a number onto text with plus.

Python cannot do that and says so.

An f-string is the fix, as in topic 3.

Check: Which line of an error message should you read first?

The last line, because it names the problem.

Watch out

A function does nothing until you call it. Defining it only tells Python the steps.

return is not print. A function that returns a value shows nothing on its own.

Read the last line of an error first. It names the problem, and the lines above only show how Python got there.

What you have learned

  • def writes a function you can reuse (6.1)
  • a parameter lets you pass a value in (6.2)
  • return sends a value back to your code (6.3)
  • an error names the problem and the line (6.4)

Where to go next

You have written code, used a list and made a decision.

That is enough to start reading other people's Python.

If you want a qualification, our data and analytics courses are regulated and lead to a certificate.

This free course does not, and nothing here counts towards one.