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…
- CoursePython Beginner Course
- Lesson1 of 10
- Video1 h 0 min
- FormatJupyter notebook · 87 code cells
What you'll learn
- How Python Runs Your Code
- Getting Set Up: Python on Your Computer
- print and Comments: Your First Words in Python
- Variables: Labelled Jars for Your Data
- Numbers and Maths: Python as a Pocket Calculator
- Strings and f-strings: Python's Text Superpowers
- input and Type Conversion: Programs That Listen
- Booleans and Comparisons: Yes-or-No Questions
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbPython 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!")
print("Step 1: wake up")
print("Step 2: make coffee")
print("Step 3: learn Python")
print(365 * 24)
print("365 * 24")
Getting Set Up: Python on Your Computer#
- Download Python 3 from python.org and run the installer. On Windows, tick 'Add Python to PATH' on the very first screen.
- Check it worked: open a terminal and type python --version
- 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 and Comments: Your First Words in Python#
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")
print("Ready", end="... ")
print("steady", end="... ")
print("go!")
print()
print("2026", "10", "09", sep="-")
# 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")
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)
temperature = 27
print("It is now", temperature, "degrees in", city)
points = 10
points = points + 5
print(points)
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)
Score = 1
score = 2
print(Score, score)
width, height = 4, 3
print("Area:", width * height)
Common mistake: a typo in a variable name#
score = 120
print(scroe)
print(score)
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"))
print(9 + 4)
print(9 - 4)
print(9 * 4)
print(9 / 4)
cookies = 17
children = 5
print("Each child gets", cookies // children)
print("Left in the jar:", cookies % children)
print(2 ** 10)
print(9 ** 0.5)
print(14 % 2, 15 % 2)
print(2 + 3 * 4)
print((2 + 3) * 4)
print(10 - 2 ** 3 / 4)
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)
bill = 100 / 3
print(bill)
print(round(bill, 2))
Quick check: what do 23 // 4 and 23 % 4 give?#
print(23 // 4, 23 % 4)
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")
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))
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)
print(len(full_name))
print(full_name.upper())
print(full_name.lower())
print(full_name.replace("Ada", "Grace"))
messy = " hello WORLD "
print("[" + messy + "]")
print("[" + messy.strip() + "]")
print(messy.strip().title())
word = "Python"
print(word[0])
print(word[-1])
print(word[0:3])
print("It's a lovely day")
print('She said "wow" and left')
print("Line one\nLine two")
print("Name:\tAda")
sentence = "the cat sat on the mat"
print(sentence.count("at"))
print(sentence.startswith("the"))
print(sentence.find("sat"))
Common mistake: gluing text and numbers together#
age = 25
print("Age: " + age)
print("Age: " + str(age))
print(f"Age: {age}")
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}")
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:,}")
Pro tip: reach for an f-string whenever you mix text and values. It's the modern, readable way.
Your turn#
- Store your first name and your favourite food in two variables.
- 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}!")
year = input("What year were you born? ")
print(type(year))
Common mistake: doing maths with input before converting it#
print(2026 - year)
birth_year = int(year)
print(type(birth_year))
print(f"You turn {2026 - birth_year} this year")
height = float(input("Your height in metres? "))
print(f"That's {height * 100} centimetres")
print("Height as text: " + str(height))
Common mistake: converting text that isn't a number#
guests = int("twelve")
guests = int("12")
print(guests + 1)
print(int(7.9), float(3), str(45) + "6")
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}")
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))
age = int(input("How old are you? "))
can_vote = age >= 18
print(f"Old enough to vote: {can_vote}")
print(8 > 3)
print(8 < 3)
print(5 == 5)
print(5 != 5)
print(18 >= 18)
password = "sunflower42"
print(password == "Sunflower42")
print(len(password) >= 8)
print("42" in password)
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)
temperature = 22
print(temperature > 15 and temperature < 28)
print(15 < temperature < 28)
day = "Sunday"
is_weekend = day == "Saturday" or day == "Sunday"
print(f"{day}: weekend? {is_weekend}")
Quick check: what does not (5 > 3 and 2 > 4) give?#
print(5 > 3, 2 > 4)
print(not (5 > 3 and 2 > 4))
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 = 85
if battery < 20:
print("Battery low! Plug in your phone.")
else:
print(f"All good: {battery}% 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")
Common mistake: forgetting to indent#
battery = 15
if battery < 20:
print("Battery low!")
battery = 15
if battery < 20:
print("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.")
pizzas_to_order = full_pizzas
if slices_short > 0:
pizzas_to_order += 1
print(f"Order {pizzas_to_order} pizzas for {guests} 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}")
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!")
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!")
while True:
word = input("Type a word (or stop): ")
if word == "stop":
break
print(f"{word} has {len(word)} letters")
print("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}")
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)
for lap in range(1, 4):
print(f"Lap {lap} complete")
for minute in range(0, 31, 10):
print(f"{minute} minutes in")
for letter in "loop":
print(letter.upper(), end=" ")
n = 7
for i in range(1, 11):
print(f"{n} x {i:>2} = {n * i:>3}")
total = 0
for number in range(1, 101):
total += number
print(f"1 + 2 + ... + 100 = {total}")
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)
for day in range(1, 8):
if day % 2 == 0:
print(f"Day {day}: rest")
else:
print(f"Day {day}: run {day + 1} km")
Pro tip: use for when you know what to loop over; use while when you loop until something happens.
Your turn#
- Print every even number from 2 to 20 using range with a step.
- 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])
playlist.append("Sunset Walk")
playlist[1] = "City Rain (Remix)"
print(playlist)
print(len(playlist))
Common mistake: an index that doesn't exist#
print(playlist[4])
print(playlist[3])
print(playlist[len(playlist) - 1])
for song in playlist:
print(f"Now playing: {song}")
for position, song in enumerate(playlist, start=1):
print(f"{position}. {song}")
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)
squares = []
for n in range(1, 7):
squares.append(n ** 2)
print(squares)
passed = []
for score in scores:
if score >= 80:
passed.append(score)
print(f"{len(passed)} of {len(scores)} passed: {passed}")
shopping = ["milk", "eggs", "bread", "apples"]
shopping.remove("eggs")
shopping.sort()
print(shopping)
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}")
orange = (255, 165, 0)
red, green, blue = orange
print(f"Red {red}, green {green}, blue {blue}")
print(len(orange), type(orange))
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}")
Pro tip: list for a collection that grows or changes; tuple for a fixed record.
Capstone Project: Build a Cafe Till#
- Show the menu (a list of tuples)
- Take orders in a loop until the customer types 'done'
- Politely reject items that aren't on the menu
- Print an itemised receipt with a running total
- 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}")
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)}")
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}")
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}")
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!")
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!")
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#
- 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.
- Upgrade the cafe till: if a customer orders the same item twice, warn them, and print 'Free cookie!' when the total passes 15.
- 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.



