Mathew K Analytics

Lesson 1 · Python Beginner Course

Python in 60 Minutes: Write Your First Real Programs (Complete Beginner Course)

In this lesson you'll be able to: Run Python code and read its output (and its error messages) with confidence Store information in variables and do maths…

⬇ Download notebook

📓 Full notebook

Download .ipynb

Python in 60 Minutes: Write Your First Real Programs#

In this lesson you'll be able to:

  • Run Python code and read its output (and its error messages) with confidence
  • Store information in variables and do maths with it
  • Work with text using strings and f-strings
  • Write programs that ask questions and react to the answers
  • Make decisions with if, elif and else
  • Repeat work with while loops, for loops and range
  • Keep collections of data in lists and tuples Projects: Pizza Party Planner, Life in Numbers, Cinema Ticket Pricer, and a capstone: a working cafe till that takes orders and prints a receipt

How Python Runs Your Code#

A program is a list of instructions, written in a language the computer can follow. Python reads your instructions from top to bottom, one line at a time. The Python interpreter translates each line and runs it straight away. In a notebook like this one, code lives in cells, and the output appears right below.

print("Hello from Python!")
Hello from Python!
print("Step 1: wake up")
print("Step 2: make coffee")
print("Step 3: learn Python")
Step 1: wake up
Step 2: make coffee
Step 3: learn Python
print(365 * 24)
print("365 * 24")
8760
365 * 24

Getting Set Up: Python on Your Computer#

  1. Download Python 3 from python.org and run the installer. On Windows, tick 'Add Python to PATH' on the very first screen.
  2. Check it worked: open a terminal and type python --version
  3. Pick a place to write code:
    • VS Code with the Python extension: a free, popular code editor
    • Jupyter Notebook or JupyterLab: code in cells, like this video
    • No install at all? Google Colab runs notebooks in your browser

Pro tip: any Python version from 3.10 upwards will run every example in this course.

print shows values on screen. Comments are notes that Python skips.

print("I can print text")
print(42)
print("I can print several things:", 7, "days", 52, "weeks")
I can print text
42
I can print several things: 7 days 52 weeks
print("Ready", end="... ")
print("steady", end="... ")
print("go!")
print()
print("2026", "10", "09", sep="-")
Ready... steady... go!

2026-10-09
# This whole line is a comment. Python skips it completely.
print("Comments don't change the output")  # a comment can sit here too
# print("This line is switched off")
Comments don't change the output

Pro tip: write comments that explain WHY, not WHAT. The code already says what.

Variables: Labelled Jars for Your Data#

A variable is a name that points to a value, so you can use it again later. name = value puts the value into a jar with that label on it.

city = "Lisbon"
temperature = 24
print(city)
print(temperature)
Lisbon
24
temperature = 27
print("It is now", temperature, "degrees in", city)
It is now 27 degrees in Lisbon
points = 10
points = points + 5
print(points)
15

Naming rules:

  • Letters, digits and underscores only, and never start with a digit
  • Case matters: Score and score are two different variables
  • Python style is snake_case: lowercase words joined by underscores

Pro tip: name variables for what they mean: hours_slept, not h or x.

hours_slept = 7.5
favourite_band = "The Lumineers"
is_morning_person = False
print(hours_slept, favourite_band, is_morning_person)
7.5 The Lumineers False
Score = 1
score = 2
print(Score, score)

width, height = 4, 3
print("Area:", width * height)
1 2
Area: 12

Common mistake: a typo in a variable name#

score = 120
print(scroe)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[13], line 2
      1 score = 120
----> 2 print(scroe)

NameError: name 'scroe' is not defined
print(score)
120

Numbers and Maths: Python as a Pocket Calculator#

int: whole numbers like 7 or -3. float: numbers with a decimal point like 2.5

print(type(7))
print(type(2.5))
print(type("7"))
<class 'int'>
<class 'float'>
<class 'str'>
print(9 + 4)
print(9 - 4)
print(9 * 4)
print(9 / 4)
13
5
36
2.25
cookies = 17
children = 5
print("Each child gets", cookies // children)
print("Left in the jar:", cookies % children)
Each child gets 3
Left in the jar: 2
print(2 ** 10)
print(9 ** 0.5)
print(14 % 2, 15 % 2)
1024
3.0
0 1
print(2 + 3 * 4)
print((2 + 3) * 4)
print(10 - 2 ** 3 / 4)
14
20
8.0

Pro tip: brackets first, then **, then * / // %, then + and -. When in doubt, add brackets.

steps = 0
steps += 3200
steps += 4500
steps -= 700
print("Steps today:", steps)
Steps today: 7000
bill = 100 / 3
print(bill)
print(round(bill, 2))
33.333333333333336
33.33

Quick check: what do 23 // 4 and 23 % 4 give?#

print(23 // 4, 23 % 4)
5 3

Your turn#

How many minutes are there in a week? And how many whole weeks are in 1000 days?

Mini-project 1: Pizza Party Planner#

13 guests, 3 slices each, 8 slices per pizza, 11.50 per pizza. How many pizzas?

guests = 13
slices_each = 3
slices_per_pizza = 8

slices_needed = guests * slices_each
full_pizzas = slices_needed // slices_per_pizza
slices_short = slices_needed % slices_per_pizza
print(slices_needed, "slices needed")
print(full_pizzas, "full pizzas leaves us", slices_short, "slices short")
39 slices needed
4 full pizzas leaves us 7 slices short
pizzas_to_order = full_pizzas + 1
cost = pizzas_to_order * 11.50
print("Order", pizzas_to_order, "pizzas")
print("Total cost:", cost)
print("Cost per guest:", round(cost / guests, 2))
Order 5 pizzas
Total cost: 57.5
Cost per guest: 4.42

Strings and f-strings: Python's Text Superpowers#

A string is text inside quotes: "double" or 'single' both work.

first = "Ada"
last = 'Okafor'
full_name = first + " " + last
print(full_name)
print("-" * 20)
Ada Okafor
--------------------
print(len(full_name))
print(full_name.upper())
print(full_name.lower())
print(full_name.replace("Ada", "Grace"))
10
ADA OKAFOR
ada okafor
Grace Okafor
messy = "   hello WORLD   "
print("[" + messy + "]")
print("[" + messy.strip() + "]")
print(messy.strip().title())
[   hello WORLD   ]
[hello WORLD]
Hello World
word = "Python"
print(word[0])
print(word[-1])
print(word[0:3])
P
n
Pyt
print("It's a lovely day")
print('She said "wow" and left')
print("Line one\nLine two")
print("Name:\tAda")
It's a lovely day
She said "wow" and left
Line one
Line two
Name:	Ada
sentence = "the cat sat on the mat"
print(sentence.count("at"))
print(sentence.startswith("the"))
print(sentence.find("sat"))
3
True
8

Common mistake: gluing text and numbers together#

age = 25
print("Age: " + age)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[31], line 2
      1 age = 25
----> 2 print("Age: " + age)

TypeError: can only concatenate str (not "int") to str
print("Age: " + str(age))
print(f"Age: {age}")
Age: 25
Age: 25
item = "notebook"
price = 3.5
quantity = 4
print(f"{quantity} x {item} costs £{price * quantity}")
print(f"{quantity} x {item.upper()} costs £{price * quantity:.2f}")
4 x notebook costs £14.0
4 x NOTEBOOK costs £14.00
print(f"{'Item':<12}{'Price':>8}")
print(f"{'Tea':<12}{1.9:>8.2f}")
print(f"{'Flapjack':<12}{2.25:>8.2f}")
print(f"{1234567:,}")
Item           Price
Tea             1.90
Flapjack        2.25
1,234,567

Pro tip: reach for an f-string whenever you mix text and values. It's the modern, readable way.

Your turn#

  1. Store your first name and your favourite food in two variables.
  2. Print a sentence about them with an f-string, with the food in capitals.

input and Type Conversion: Programs That Listen#

input() shows a prompt, waits for the user to type, and gives back what they typed. It ALWAYS gives back a string, even if the user types a number.

name = input("What's your name? ")
print(f"Nice to meet you, {name}!")
What's your name? Maya
Nice to meet you, Maya!
year = input("What year were you born? ")
print(type(year))
What year were you born? 1998
<class 'str'>

Common mistake: doing maths with input before converting it#

print(2026 - year)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[37], line 1
----> 1 print(2026 - year)

TypeError: unsupported operand type(s) for -: 'int' and 'str'
birth_year = int(year)
print(type(birth_year))
print(f"You turn {2026 - birth_year} this year")
<class 'int'>
You turn 28 this year
height = float(input("Your height in metres? "))
print(f"That's {height * 100} centimetres")
print("Height as text: " + str(height))
Your height in metres? 1.68
That's 168.0 centimetres
Height as text: 1.68

Common mistake: converting text that isn't a number#

guests = int("twelve")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[40], line 1
----> 1 guests = int("twelve")

ValueError: invalid literal for int() with base 10: 'twelve'
guests = int("12")
print(guests + 1)
print(int(7.9), float(3), str(45) + "6")
13
7 3.0 456

Pro tip: users type surprising things. Later in this course, try/except will handle bad input.

Mini-project 2: Your Life in Numbers#

Ask for a name and an age, then turn the age into some surprising statistics.

name = input("Your name: ")
age = int(input("Your age in years: "))

days = age * 365
heartbeats = days * 24 * 60 * 70
years_asleep = age / 3

print(f"--- {name.title()}'s life in numbers ---")
print(f"Days lived:       about {days:,}")
print(f"Heartbeats:       about {heartbeats:,}")
print(f"Years spent asleep: about {years_asleep:.1f}")
Your name: sam
Your age in years: 30
--- Sam's life in numbers ---
Days lived:       about 10,950
Heartbeats:       about 1,103,760,000
Years spent asleep: about 10.0

Booleans and Comparisons: Yes-or-No Questions#

A boolean is either True or False. Comparisons produce booleans. == equal != not equal > < >= <=

is_raining = True
print(is_raining)
print(type(is_raining))
True
<class 'bool'>
age = int(input("How old are you? "))
can_vote = age >= 18
print(f"Old enough to vote: {can_vote}")
How old are you? 16
Old enough to vote: False
print(8 > 3)
print(8 < 3)
print(5 == 5)
print(5 != 5)
print(18 >= 18)
True
False
True
False
True
password = "sunflower42"
print(password == "Sunflower42")
print(len(password) >= 8)
print("42" in password)
False
True
True

Watch out: = stores a value, == compares two values. Mixing them up is a classic slip.

and, or, not: Combining Conditions#

and: True only if BOTH sides are True or: True if AT LEAST ONE side is True not: flips True to False and False to True

has_ticket = True
has_id = False
print("Both:", has_ticket and has_id)
print("Either:", has_ticket or has_id)
print("No ID:", not has_id)
Both: False
Either: True
No ID: True
temperature = 22
print(temperature > 15 and temperature < 28)
print(15 < temperature < 28)
True
True
day = "Sunday"
is_weekend = day == "Saturday" or day == "Sunday"
print(f"{day}: weekend? {is_weekend}")
Sunday: weekend? True

Quick check: what does not (5 > 3 and 2 > 4) give?#

print(5 > 3, 2 > 4)
print(not (5 > 3 and 2 > 4))
True False
True

if, elif, else: Programs That Make Decisions#

if condition: code that runs only when the condition is True Indentation (4 spaces) shows Python which lines belong to the if.

battery = 15
if battery < 20:
    print("Battery low! Plug in your phone.")
print("Battery check finished")
Battery low! Plug in your phone.
Battery check finished
battery = 85
if battery < 20:
    print("Battery low! Plug in your phone.")
else:
    print(f"All good: {battery}% left")
All good: 85% left
wind_speed = 48
if wind_speed < 10:
    print("Calm: perfect for a picnic")
elif wind_speed < 30:
    print("Breezy: fly a kite")
elif wind_speed < 60:
    print("Windy: hold on to your hat")
else:
    print("Storm: stay indoors")
Windy: hold on to your hat

Common mistake: forgetting to indent#

battery = 15
if battery < 20:
print("Battery low!")
  Cell In[54], line 3
    print("Battery low!")
    ^
IndentationError: expected an indented block after 'if' statement on line 2
battery = 15
if battery < 20:
    print("Battery low!")
Battery low!
username = input("Username: ")
pin = input("PIN: ")
if username == "admin" and pin == "2468":
    print("Welcome back, admin!")
elif username == "admin":
    print("Wrong PIN, try again.")
else:
    print("Unknown user.")
Username: admin
PIN: 1234
Wrong PIN, try again.
pizzas_to_order = full_pizzas
if slices_short > 0:
    pizzas_to_order += 1
print(f"Order {pizzas_to_order} pizzas for {guests} guests")
Order 5 pizzas for 12 guests

Pro tip: give each variable one job. Reusing names for different things causes sneaky bugs.

Mini-project 3: Cinema Ticket Pricer#

Under 12: 6.00 Age 65+: 7.50 Everyone else: 11.00 Tuesdays: 30% off every ticket. Students get 2.00 off adult tickets.

age = int(input("How old are you? "))
day = input("What day is it? ").strip().lower()
student = input("Are you a student? (yes/no) ").strip().lower() == "yes"

if age < 12:
    price = 6.00
elif age >= 65:
    price = 7.50
elif student:
    price = 11.00 - 2.00
else:
    price = 11.00

if day == "tuesday":
    price = price * 0.7
print(f"Your ticket costs £{price:.2f}")
How old are you? 19
What day is it?   Tuesday
Are you a student? (yes/no) yes
Your ticket costs £6.30

Your turn#

Add a rule to the ticket pricer: anyone with a 'GOLD' membership code gets in free. Hint: one more input(), and one more if, placed before the final print.

while Loops: Repeat Until It's Done#

while condition: this block repeats for as long as the condition stays True

countdown = 5
while countdown > 0:
    print(countdown)
    countdown -= 1
print("Lift off!")
5
4
3
2
1
Lift off!

Watch out: if the condition never becomes False, the loop runs forever. In Jupyter, press the stop button (or Ctrl+C in a terminal) to break out.

savings = 0
week = 0
while savings < 100:
    week += 1
    savings += 15
    print(f"Week {week}: £{savings}")
print(f"Goal reached in {week} weeks!")
Week 1: £15
Week 2: £30
Week 3: £45
Week 4: £60
Week 5: £75
Week 6: £90
Week 7: £105
Goal reached in 7 weeks!
while True:
    word = input("Type a word (or stop): ")
    if word == "stop":
        break
    print(f"{word} has {len(word)} letters")
print("Bye!")
Type a word (or stop): banana
banana has 6 letters
Type a word (or stop): sky
sky has 3 letters
Type a word (or stop): extraordinary
extraordinary has 13 letters
Type a word (or stop): stop
Bye!
code = input("Choose a 4-digit door code: ")
while len(code) != 4 or not code.isdigit():
    print("  That's not 4 digits.")
    code = input("Choose a 4-digit door code: ")
print(f"Door code set to {code}")
Choose a 4-digit door code: 12
  That's not 4 digits.
Choose a 4-digit door code: 12ab
  That's not 4 digits.
Choose a 4-digit door code: 7351
Door code set to 7351

for Loops and range: Counting Made Simple#

for item in sequence: runs the block once for each item range(5) -> 0 1 2 3 4 range(1, 6) -> 1 2 3 4 5 range(0, 20, 5) -> 0 5 10 15

for number in range(5):
    print(number)
0
1
2
3
4
for lap in range(1, 4):
    print(f"Lap {lap} complete")

for minute in range(0, 31, 10):
    print(f"{minute} minutes in")
Lap 1 complete
Lap 2 complete
Lap 3 complete
0 minutes in
10 minutes in
20 minutes in
30 minutes in
for letter in "loop":
    print(letter.upper(), end=" ")
L O O P 
n = 7
for i in range(1, 11):
    print(f"{n} x {i:>2} = {n * i:>3}")
7 x  1 =   7
7 x  2 =  14
7 x  3 =  21
7 x  4 =  28
7 x  5 =  35
7 x  6 =  42
7 x  7 =  49
7 x  8 =  56
7 x  9 =  63
7 x 10 =  70
total = 0
for number in range(1, 101):
    total += number
print(f"1 + 2 + ... + 100 = {total}")
1 + 2 + ... + 100 = 5050
for row in range(1, 6):
    print(" " * (5 - row) + "*" * (2 * row - 1))
    *
   ***
  *****
 *******
*********

Quick check: how many times does for x in range(2, 10, 3) loop?#

for x in range(2, 10, 3):
    print(x)
2
5
8
for day in range(1, 8):
    if day % 2 == 0:
        print(f"Day {day}: rest")
    else:
        print(f"Day {day}: run {day + 1} km")
Day 1: run 2 km
Day 2: rest
Day 3: run 4 km
Day 4: rest
Day 5: run 6 km
Day 6: rest
Day 7: run 8 km

Pro tip: use for when you know what to loop over; use while when you loop until something happens.

Your turn#

  1. Print every even number from 2 to 20 using range with a step.
  2. Use a while loop to find how many times you can double 1 before it passes 1000.

Lists and Tuples: Keeping Things Together#

A list holds many values, in order, inside square brackets. You can change it.

playlist = ["Morning Light", "City Rain", "Night Drive"]
print(playlist)
print(len(playlist))
print(playlist[0])
print(playlist[-1])
['Morning Light', 'City Rain', 'Night Drive']
3
Morning Light
Night Drive
playlist.append("Sunset Walk")
playlist[1] = "City Rain (Remix)"
print(playlist)
print(len(playlist))
['Morning Light', 'City Rain (Remix)', 'Night Drive', 'Sunset Walk']
4

Common mistake: an index that doesn't exist#

print(playlist[4])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[73], line 1
----> 1 print(playlist[4])

IndexError: list index out of range
print(playlist[3])
print(playlist[len(playlist) - 1])
Sunset Walk
Sunset Walk
for song in playlist:
    print(f"Now playing: {song}")

for position, song in enumerate(playlist, start=1):
    print(f"{position}. {song}")
Now playing: Morning Light
Now playing: City Rain (Remix)
Now playing: Night Drive
Now playing: Sunset Walk
1. Morning Light
2. City Rain (Remix)
3. Night Drive
4. Sunset Walk
scores = [72, 88, 95, 64, 81]
print(f"Highest: {max(scores)}, lowest: {min(scores)}")
print(f"Average: {sum(scores) / len(scores)}")
print(95 in scores, 100 in scores)
Highest: 95, lowest: 64
Average: 80.0
True False
squares = []
for n in range(1, 7):
    squares.append(n ** 2)
print(squares)
[1, 4, 9, 16, 25, 36]
passed = []
for score in scores:
    if score >= 80:
        passed.append(score)
print(f"{len(passed)} of {len(scores)} passed: {passed}")
3 of 5 passed: [88, 95, 81]
shopping = ["milk", "eggs", "bread", "apples"]
shopping.remove("eggs")
shopping.sort()
print(shopping)
['apples', 'bread', 'milk']

A tuple is like a list in round brackets, but it can't be changed once it's made. Use tuples for values that belong together: a coordinate, a date, a menu item and its price.

harbour = (38.69, -9.21)
print(harbour[0])
latitude, longitude = harbour
print(f"Latitude {latitude}, longitude {longitude}")
38.69
Latitude 38.69, longitude -9.21
orange = (255, 165, 0)
red, green, blue = orange
print(f"Red {red}, green {green}, blue {blue}")
print(len(orange), type(orange))
Red 255, green 165, blue 0
3 <class 'tuple'>
week = [("Mon", 6200), ("Tue", 9800), ("Wed", 4100),
        ("Thu", 11300), ("Fri", 7600)]
for day, steps in week:
    bar = "#" * (steps // 500)
    print(f"{day} {steps:>6,} {bar}")
Mon  6,200 ############
Tue  9,800 ###################
Wed  4,100 ########
Thu 11,300 ######################
Fri  7,600 ###############

Pro tip: list for a collection that grows or changes; tuple for a fixed record.

Capstone Project: Build a Cafe Till#

  1. Show the menu (a list of tuples)
  2. Take orders in a loop until the customer types 'done'
  3. Politely reject items that aren't on the menu
  4. Print an itemised receipt with a running total
  5. Apply a 10% loyalty discount, then take payment and give change
menu = [("coffee", 2.80), ("tea", 1.90), ("croissant", 2.40),
        ("bagel", 3.20), ("smoothie", 4.50)]

print("=== THE CORNER CAFE ===")
for item, price in menu:
    print(f"  {item.title():<12} £{price:.2f}")
=== THE CORNER CAFE ===
  Coffee       £2.80
  Tea          £1.90
  Croissant    £2.40
  Bagel        £3.20
  Smoothie     £4.50
order = []
while True:
    choice = input("What would you like? (or done) ").strip().lower()
    if choice == "done":
        break
    price = 0
    for item, item_price in menu:
        if item == choice:
            price = item_price
    if price == 0:
        print(f"  Sorry, we don't sell {choice}.")
    else:
        quantity = int(input(f"How many {choice}? "))
        order.append((choice, quantity, price))
        print(f"  Added {quantity} x {choice}")
print(f"Items in order: {len(order)}")
What would you like? (or done) Coffee
How many coffee? 2
  Added 2 x coffee
What would you like? (or done) pizza
  Sorry, we don't sell pizza.
What would you like? (or done) croissant
How many croissant? 1
  Added 1 x croissant
What would you like? (or done)  SMOOTHIE 
How many smoothie? 1
  Added 1 x smoothie
What would you like? (or done) done
Items in order: 3
subtotal = 0
print("-" * 11, "RECEIPT", "-" * 10)
for item, quantity, price in order:
    line_total = quantity * price
    subtotal += line_total
    print(f"{quantity} x {item:<20}{line_total:>6.2f}")
print("-" * 30)
print(f"{'Subtotal':<24}{subtotal:>6.2f}")
----------- RECEIPT ----------
2 x coffee                5.60
1 x croissant             2.40
1 x smoothie              4.50
------------------------------
Subtotal                 12.50
member = input("Loyalty card? (yes/no) ").strip().lower() == "yes"
discount = 0
if member and subtotal >= 10:
    discount = subtotal * 0.10
elif member:
    print("  Spend £10 or more to unlock your 10% discount")
total = subtotal - discount
print(f"{'Discount':<24}{-discount:>6.2f}")
print(f"{'TOTAL (£)':<24}{total:>6.2f}")
Loyalty card? (yes/no) yes
Discount                 -1.25
TOTAL (£)                11.25
paid = float(input("Cash handed over: £"))
while paid < total:
    print(f"  Still £{total - paid:.2f} to pay")
    paid += float(input("More cash: £"))
print(f"Change: £{paid - total:.2f}")
print("Thank you for visiting The Corner Cafe!")
Cash handed over: £10
  Still £1.25 to pay
More cash: £5
Change: £3.75
Thank you for visiting The Corner Cafe!
items_bought = 0
for item, quantity, price in order:
    items_bought += quantity
print(f"You bought {items_bought} items today.")
if items_bought >= 4:
    print("You've earned a stamp on your coffee card!")
You bought 4 items today.
You've earned a stamp on your coffee card!

Pro tip: build big programs in small, runnable steps, and test each step before the next.

Recap#

  • print shows output; # starts a comment
  • Variables are labelled jars: name = value
  • int and float for numbers: + - * / // % ** and brackets for order
  • Strings: len, .upper(), .strip(), indexes from 0, and f-strings with {value:.2f}
  • input() always returns a string: convert with int(), float(), str()
  • Booleans and comparisons: == != > < >= <=, combined with and, or, not
  • if / elif / else make decisions; indentation shows what belongs where
  • while repeats until a condition is False; for loops over range, strings and lists
  • Lists change (append, index, len); tuples stay fixed and unpack neatly

Try it yourself#

  1. Tip calculator: ask for the bill and the number of people, then print each share for tips of 10%, 15% and 20% using a for loop over a list.
  2. Upgrade the cafe till: if a customer orders the same item twice, warn them, and print 'Free cookie!' when the total passes 15.
  3. Times-table quiz: ask 5 multiplication questions in a loop, check each answer, and print a score out of 5 at the end.

What's next#

Lesson 2: Python Essentials: Think Like a Programmer Functions, dictionaries, more string and list power, and breaking problems into steps.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.