← All notes

Python Basics, up to Classes

Study guide · 28 Sep 2026

AI-generated Written with AI, solely for personal reference.

A quick path through core Python 3, in the order you’d learn it. Every example runs as-is: paste it into a file and run python3 file.py, or try lines in the interactive shell by typing python3.

1. Running Python

python3 --version        # check it's installed
python3                  # interactive shell; exit() to leave
python3 hello.py         # run a file
print("Hello, world!")

Comments start with #. Indentation (4 spaces) is part of the syntax: it marks which lines belong to a block.

2. Variables and types

A variable is a name for a value. You don’t declare types; Python works them out.

name = "Maxine"          # str   (text)
age = 30                 # int   (whole number)
height = 1.75            # float (decimal)
is_active = True         # bool  (True / False)
nothing = None           # None  (no value)

print(type(age))         # <class 'int'>

# Converting between types
print(int("42") + 1)     # 43
print(str(3.5) + "!")    # 3.5!
print(float("2"))        # 2.0

3. Numbers and operators

print(7 + 2, 7 - 2, 7 * 2)   # 9 5 14
print(7 / 2)                 # 3.5  true division
print(7 // 2)                # 3    floor division
print(7 % 2)                 # 1    remainder
print(2 ** 10)               # 1024 power

count = 0
count += 1                   # same as count = count + 1

# Comparisons give booleans
print(3 > 2, 3 == 3, 3 != 4)         # True True True
print(1 < 5 and 5 < 10, not True)    # True False

4. Strings

greeting = "hello world"

print(greeting.upper())              # HELLO WORLD
print(greeting.title())              # Hello World
print(greeting.replace("world", "Python"))
print(greeting.split())              # ['hello', 'world']
print(len(greeting))                 # 11
print("world" in greeting)           # True

# Indexing and slicing (positions start at 0)
print(greeting[0])       # h
print(greeting[-1])      # d (last character)
print(greeting[0:5])     # hello

# f-strings put values inside text
name, score = "Aisha", 92.456
print(f"{name} scored {score:.1f}")  # Aisha scored 92.5

Strings can’t be changed in place; methods like upper() return a new string.

5. Lists

An ordered collection you can change.

fruits = ["apple", "banana", "cherry"]

fruits.append("date")        # add to the end
fruits.insert(0, "avocado")  # add at a position
fruits.remove("banana")      # remove by value
last = fruits.pop()          # remove and return the last item

print(fruits)                # ['avocado', 'apple', 'cherry']
print(fruits[1], len(fruits))  # apple 3
print(sorted(fruits, reverse=True))

numbers = [3, 1, 2]
numbers.sort()               # sorts in place
print(numbers, sum(numbers), max(numbers))  # [1, 2, 3] 6 3

6. Tuples, dictionaries and sets

# Tuple: ordered, cannot be changed
point = (3, 4)
x, y = point                 # unpacking
print(x, y)                  # 3 4

# Dictionary: key -> value
person = {"name": "Maxine", "city": "Springfield"}
person["role"] = "Engineer"          # add or update
print(person["name"])                # Maxine
print(person.get("age", "unknown"))  # unknown (no error if missing)

for key, value in person.items():
    print(key, "=", value)

# Set: unique items, no order
tags = {"python", "code", "python"}
print(tags)                          # {'python', 'code'} (order may vary)
print("code" in tags)                # True
Type Ordered Changeable Duplicates Example
list yes yes yes [1, 2, 2]
tuple yes no yes (1, 2, 2)
dict yes (insertion) yes keys unique {"a": 1}
set no yes no {1, 2}

7. Built-in functions

Python has a set of functions that are always available, no import needed.

Function What it does Example → result
print(x) Show a value print("hi") → hi
input(prompt) Read a line typed by the user, as a string input("Name? ")
len(x) Number of items or characters len([1, 2, 3]) → 3
type(x) The type of a value type(3.0) → <class 'float'>
int(), float(), str(), bool() Convert between types int("7") → 7
list(), tuple(), set(), dict() Build or convert collections list("abc") → ['a', 'b', 'c']
min(x), max(x) Smallest / largest item max([3, 9, 2]) → 9
sum(x) Add up numbers sum([1, 2, 3]) → 6
abs(x) Distance from zero abs(-5) → 5
round(x, n) Round to n decimal places round(3.14159, 2) → 3.14
sorted(x) New sorted list sorted([3, 1, 2]) → [1, 2, 3]
reversed(x) Items in reverse order list(reversed([1, 2, 3])) → [3, 2, 1]
range(start, stop, step) A sequence of numbers list(range(0, 10, 3)) → [0, 3, 6, 9]
enumerate(x), zip(a, b) Loop with positions / over two lists at once see Loops
any(x), all(x) Is at least one / every item true? all([True, False]) → False
isinstance(x, t) Is x of type t? isinstance(5, int) → True
help(x), dir(x) Documentation / available attributes, in the shell help(str.split)
scores = [72, 95, 88, 61]

print(len(scores), min(scores), max(scores))   # 4 61 95
print(round(sum(scores) / len(scores), 1))     # 79.0 (the average)
print(sorted(scores, reverse=True))            # [95, 88, 72, 61]
print(list(reversed(scores)))                  # [61, 88, 95, 72]
print(any(s > 90 for s in scores))             # True: someone scored over 90
print(all(s >= 60 for s in scores))            # True: everyone passed
print(abs(-7), int("12") + 3, list("hey"))     # 7 15 ['h', 'e', 'y']
print(set([1, 1, 2]), dict(a=1, b=2))          # {1, 2} {'a': 1, 'b': 2}

input() always returns text, so convert it before doing maths:

age = int(input("How old are you? "))
print(f"Next year you'll be {age + 1}")

8. Conditions

temperature = 31

if temperature > 30:
    print("Hot")
elif temperature > 20:
    print("Warm")
else:
    print("Cool")

# One-line version
age = 30
status = "adult" if age >= 18 else "minor"
print(status)                # adult

# Empty values count as False
items = []
if not items:
    print("No items")

9. Loops

for fruit in ["apple", "banana"]:
    print(fruit)

for i in range(3):           # 0, 1, 2
    print(i)

for i, fruit in enumerate(["apple", "banana"], start=1):
    print(i, fruit)          # 1 apple / 2 banana

names = ["Ali", "Siti"]
scores = [80, 95]
for name, score in zip(names, scores):
    print(name, score)

count = 3
while count > 0:
    print(count)
    count -= 1

for n in range(10):
    if n == 2:
        continue             # skip to the next item
    if n == 5:
        break                # stop the loop
    print(n)                 # 0 1 3 4

10. Comprehensions

A short way to build a collection from a loop.

squares = [n * n for n in range(5)]              # [0, 1, 4, 9, 16]
evens = [n for n in range(10) if n % 2 == 0]     # [0, 2, 4, 6, 8]
lengths = {word: len(word) for word in ["hi", "hello"]}  # {'hi': 2, 'hello': 5}
print(squares, evens, lengths)

11. Functions

def greet(name, greeting="Hello"):
    """Return a greeting. The text in triple quotes is the docstring."""
    return f"{greeting}, {name}!"

print(greet("Maxine"))                   # Hello, Maxine!
print(greet("Maxine", greeting="Hi"))    # Hi, Maxine!

def total(*numbers):                     # any number of positional arguments
    return sum(numbers)

def describe(**details):                 # any number of keyword arguments
    return ", ".join(f"{k}={v}" for k, v in details.items())

print(total(1, 2, 3))                    # 6
print(describe(lang="Python", level=1))  # lang=Python, level=1

# Small anonymous function, often used for sorting
words = ["banana", "kiwi", "apple"]
print(sorted(words, key=lambda w: len(w)))  # ['kiwi', 'apple', 'banana']

A function without return returns None. Variables created inside a function exist only inside it.

12. Handling errors

def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Can't divide by zero")
        return None
    else:
        return result            # runs only if no error happened
    finally:
        print("Done")            # always runs

print(safe_divide(10, 2))        # Done / 5.0
print(safe_divide(1, 0))         # Can't divide by zero / Done / None

def set_age(age):
    if age < 0:
        raise ValueError("age can't be negative")
    return age

try:
    set_age(-1)
except ValueError as error:
    print(f"Error: {error}")     # Error: age can't be negative

13. Files

with closes the file for you, even if an error happens.

with open("notes.txt", "w") as f:        # "w" overwrites, "a" appends
    f.write("first line\n")
    f.write("second line\n")

with open("notes.txt") as f:             # default mode "r" reads
    for line in f:
        print(line.strip())

14. Modules

import math
from datetime import date
import random as rnd

print(math.sqrt(16))         # 4.0
print(date.today().year)
print(rnd.randint(1, 6))     # a dice roll

Any .py file is a module. Code under if __name__ == "__main__": runs only when the file is run directly, not when it’s imported:

def main():
    print("Running as a script")

if __name__ == "__main__":
    main()

15. Classes

A class is a blueprint that bundles data (attributes) with the functions that act on it (methods). Each object made from it is an instance.

class BankAccount:
    bank_name = "Python Bank"            # class attribute, shared by all

    def __init__(self, owner, balance=0):
        self.owner = owner               # instance attributes
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self.balance += amount
        return self.balance

    def __repr__(self):                  # how the object prints
        return f"BankAccount({self.owner!r}, balance={self.balance})"

account = BankAccount("Maxine", 100)
account.deposit(50)
print(account.balance)       # 150
print(account)               # BankAccount('Maxine', balance=150)
print(account.bank_name)     # Python Bank
  • __init__ runs when you create an instance and sets it up.
  • self is the instance itself; every method takes it as the first parameter.
  • Methods with double underscores, like __repr__, hook into built-in behaviour.

Inheritance

A child class gets everything from its parent and can add or override behaviour.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "..."

    def introduce(self):
        return f"{self.name} says {self.speak()}"

class Dog(Animal):
    def speak(self):                     # override
        return "Woof"

class Puppy(Dog):
    def __init__(self, name, age):
        super().__init__(name)           # run the parent's setup
        self.age = age

for pet in [Animal("Generic"), Dog("Rex"), Puppy("Bit", 1)]:
    print(pet.introduce())
# Generic says ... / Rex says Woof / Bit says Woof

print(isinstance(Puppy("Bit", 1), Animal))   # True

Dataclasses

For classes that mainly hold data, @dataclass writes __init__, __repr__ and == for you.

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float = 0.0

    def distance_from_origin(self):
        return (self.x ** 2 + self.y ** 2) ** 0.5

p = Point(3, 4)
print(p)                          # Point(x=3, y=4)
print(p.distance_from_origin())   # 5.0
print(p == Point(3, 4))           # True