Python Basics

Download notebook

This lesson covers the building blocks: running code, doing arithmetic, storing values in variables, and understanding data types. Type these examples into Google Colab as you go.

Google Colab

Google Colab organises code into cells that you run independently.

  1. Click + Code to add a new cell.
  2. Type Python code in the cell.
  3. Press Shift + Enter to run it (or click the play button).
  4. Output appears directly below.

Try it:

print("Hello, Colab!")
Hello, Colab!
1 + 2
3

One thing to know: variables you create in one cell carry over to later cells. The order you run cells in matters. If something isn’t working, try running all cells from the top (Runtime > Run all).

Basic Calculations

Python works as a calculator.

Operator Description Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 5 / 2 2.5
// Floor division 5 // 2 2
% Remainder 5 % 2 1
** Power 2 ** 3 8

Try this:

7 * 94 / (3**2 - 1)
82.25

Python follows the standard mathematical order of operations: parentheses first, then exponents, then multiplication/division, then addition/subtraction. When in doubt, use parentheses to make your intent clear.

# Multiplication happens before addition
5 + 2 * 3
11
# Parentheses override the default order
(5 + 2) * 3
21

Variables

Variables store values so you can reuse them.

city = "Madrid"
print(city)
Madrid

You create a variable with =, which means “assign” (not “equals”). The name goes on the left, the value on the right.

Variables become useful when you build on previous results:

temp_day_1 = 21
temp_day_2 = 34
temp_diff = temp_day_2 - temp_day_1
print(temp_diff)
13

Naming Variables

Two rules:

  1. Use lowercase letters with underscores between words (snake_case). Names can’t start with a number.
  2. Use descriptive names. Your code should read clearly, not like algebra.

Compare:

a = 21
b = 34
d = b - a
print(d)
13
temp_day_1 = 21
temp_day_2 = 34
temp_diff = temp_day_2 - temp_day_1
print(temp_diff)
13

Both produce the same result, but the second tells you what the numbers mean.

TipCase Sensitivity

Python is case-sensitive: myvariable, MyVariable, and MYVARIABLE are three different names. Stick to snake_case and you won’t run into this.

Comments

Comments are notes in your code that Python ignores. Use # to start one.

# Calculate the temperature difference
temp_diff = temp_day_2 - temp_day_1  # in degrees Celsius

Good comments explain why, not what. If the code already makes sense on its own, it doesn’t need a comment. If the reasoning behind a line isn’t obvious, a comment helps.

You don’t need to comment every line. Comment the parts that would confuse someone reading your code for the first time (including future you).

Types

Every value in Python has a type. The four you’ll use most:

  • int: Whole numbers like 5, -10, 0
  • float: Decimal numbers like 5.0, -10.5
  • str: Text (strings) like "hello", 'Madrid'
  • bool: True or False

You can check a value’s type with type():

print(type(42))
print(type(3.14))
print(type("Hello"))
print(type(True))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

Strings

Strings are text enclosed in quotes, either single (') or double ("):

print("This works")
print('So does this')
This works
So does this

If you need quotes inside a string, use the other kind as the outer quotes:

print('She said "hello"')
print("It's working")
She said "hello"
It's working

f-Strings

f-strings let you embed variables directly in text. Prefix the string with f and wrap variables in curly braces:

name = "Alice"
age = 25
print(f"My name is {name}, and I am {age} years old.")
My name is Alice, and I am 25 years old.

You can put expressions inside the braces too:

width = 5
height = 10
print(f"The area is {width * height}.")
The area is 50.

You’ll use f-strings constantly. They’re the cleanest way to combine text and values.

Mixing Types

Python won’t let you combine incompatible types:

# Uncomment to see the error:
# print(5 + "hello")  # TypeError

If you need to combine types, convert explicitly:

age = 25
print("I am " + str(age) + " years old")
I am 25 years old

(Or use an f-string, which handles the conversion for you.)

You can also convert strings to numbers when needed:

text = "25"
number = int(text)
print(number + 10)
35

Integers and floats mix freely. Python promotes the result to a float:

result = 10 + 3.5
print(result)
print(type(result))
13.5
<class 'float'>
TipWhen types go wrong

If you get a TypeError, it almost always means you’re trying to combine types that Python doesn’t know how to mix. Check what types your variables actually are with type().

Challenges

1. Variables and f-Strings

Create variables for your name, age, and a city you’d like to visit. Print a sentence using an f-string that reads: “My name is [name], I’m [age] years old, and I’d like to visit [city].”

name = "Alex"
age = 25
city = "Madrid"
print(f"My name is {name}, I'm {age} years old, and I'd like to visit {city}.")
My name is Alex, I'm 25 years old, and I'd like to visit Madrid.

2. Minutes in a Week

Calculate how many minutes there are in a week. Use variables for each step and comments to explain your logic.

days_in_week = 7
hours_in_day = 24
minutes_in_hour = 60
total_minutes = days_in_week * hours_in_day * minutes_in_hour

print(f"There are {total_minutes} minutes in a week")
There are 10080 minutes in a week

3. Temperature Converter

Convert 98.6°F to Celsius using the formula: C = (F - 32) × 5/9

fahrenheit = 98.6
celsius = (fahrenheit - 32) * 5 / 9
print(f"{fahrenheit}°F is equal to {celsius:.1f}°C")
98.6°F is equal to 37.0°C

4. String vs. Number Addition

Create two variables: num1 = "123" and num2 = "456". Add them together as strings, then convert them to integers and add again. Print both results. Why are they different?

num1 = "123"
num2 = "456"

# As strings: Python concatenates (joins) them
string_result = num1 + num2
print(f"String result: {string_result}")

# As integers: Python adds them
integer_result = int(num1) + int(num2)
print(f"Integer result: {integer_result}")
String result: 123456
Integer result: 579

5. Rectangle Calculator

Calculate the area and perimeter of a 5 × 3 rectangle. Use descriptive variable names and at least one comment.

width = 5
height = 3

area = width * height
perimeter = 2 * (width + height)

print(f"Rectangle: {width} x {height}")
print(f"Area: {area}")
print(f"Perimeter: {perimeter}")
Rectangle: 5 x 3
Area: 15
Perimeter: 16