Back to Python Examples

Basic Python

A quick-reference instruction sheet covering the fundamentals of Python programming.

Contents

  1. What is Python?
  2. Variables & Data Types
  3. Operators
  4. Strings
  5. Lists
  6. Dictionaries & Sets
  7. Control Structures
  8. Loops
  9. Functions
  10. Modules & Imports
  11. File I/O
  12. Intro to OOP

1. What is Python?

Python is a high-level, interpreted programming language known for its clean, readable syntax. It is widely used for web development, data science, automation, and scripting.

# Single-line comment

"""
Multi-line string / docstring
Often used as a comment block
"""

print("Hello, World!")

2. Variables & Data Types

Variables are created by assignment — no keyword needed.

name    = "Alice"      # str
age     = 30            # int
price   = 9.99          # float
active  = True          # bool (capital T/F)
nothing = None          # NoneType

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

# Multiple assignment
x, y, z = 1, 2, 3

# Type conversion
int("42")               # 42
float("3.14")           # 3.14
str(100)                # "100"
bool(0)                 # False
TypeExampleDescription
str"hello"Text
int42Whole numbers
float3.14Decimal numbers
boolTrue / FalseBoolean values
NoneNoneAbsence of a value
list[1, 2, 3]Ordered, mutable sequence
tuple(1, 2, 3)Ordered, immutable sequence
dict{"key": "val"}Key-value pairs
set{1, 2, 3}Unordered, unique values

3. Operators

Arithmetic

a, b = 10, 3
a + b      # 13  — addition
a - b      # 7   — subtraction
a * b      # 30  — multiplication
a / b      # 3.333… — true division (always float)
a // b     # 3   — floor division (integer result)
a % b      # 1   — modulus (remainder)
a ** b     # 1000 — exponentiation

Comparison

x == y    # equal
x != y    # not equal
x <  y    # less than
x >  y    # greater than
x <= y    # less than or equal
x >= y    # greater than or equal

Logical

a and b   # True if both are truthy
a or  b   # True if either is truthy
not a      # inverts the boolean

Identity & Membership

x is y          # True if same object in memory
x is not y      # True if different objects
"a" in "apple"   # True — membership test
3 not in [1, 2]  # True
Use is to compare identity (e.g. x is None), and == to compare values.

4. Strings

first = "Alice"
last  = "Smith"

# Concatenation
first + " " + last          # "Alice Smith"

# f-strings (Python 3.6+) — preferred
f"Hello, {first}!"           # "Hello, Alice!"
f"Age next year: {age + 1}"  # expressions work too

# Common string methods
len("hello")                  # 5
"hello".upper()               # "HELLO"
"HELLO".lower()               # "hello"
"  hello  ".strip()          # "hello"
"hello".replace("l", "r")    # "herro"
"hello".startswith("he")     # True
"hello".find("l")             # 2
"a,b,c".split(",")           # ["a","b","c"]
"-".join(["a", "b"])         # "a-b"
"hello"[1:4]                  # "ell" — slicing
"hello"[::-1]                 # "olleh" — reversed

5. Lists

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

fruits[0]                     # "apple"
fruits[-1]                    # "cherry" (last item)
fruits[1:3]                   # ["banana","cherry"] — slice
len(fruits)                   # 3
fruits.append("date")         # add to end
fruits.insert(1, "avocado")   # insert at index
fruits.remove("banana")       # remove by value
fruits.pop()                   # remove & return last
fruits.sort()                  # sort in place
fruits.reverse()               # reverse in place
"apple" in fruits             # True

List Comprehensions

# [expression for item in iterable if condition]
squares = [x**2 for x in range(5)]
# [0, 1, 4, 9, 16]

evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]

Tuples

point = (10, 20)       # immutable — cannot be changed
x, y = point           # unpacking

6. Dictionaries & Sets

Dictionaries

person = {
    "name": "Alice",
    "age":  30,
    "city": "NYC",
}

person["name"]               # "Alice"
person.get("email", "n/a")  # "n/a" — safe access with default
person["email"] = "a@b.com" # add / update
del person["city"]           # remove key

person.keys()                 # dict_keys(["name","age","email"])
person.values()               # dict_values([...])
person.items()                # dict_items([("name","Alice"),…])
"name" in person             # True

# Dict comprehension
squares = {x: x**2 for x in range(5)}
# {0:0, 1:1, 2:4, 3:9, 4:16}

Sets

colors = {"red", "green", "blue"}   # unique values only
colors.add("yellow")
colors.remove("red")
"green" in colors                  # True

a = {1, 2, 3}; b = {2, 3, 4}
a | b    # {1,2,3,4} — union
a & b    # {2,3}     — intersection
a - b    # {1}       — difference

7. Control Structures

if / elif / else

score = 75

if score >= 90:
    print("A")
elif score >= 75:
    print("B")
elif score >= 60:
    print("C")
else:
    print("F")

Ternary (Conditional Expression)

status = "adult" if age >= 18 else "minor"

match / case (Python 3.10+)

match command:
    case "quit":
        print("Quitting")
    case "help":
        print("Showing help")
    case _:
        print("Unknown command")

8. Loops

for

# Iterate over a list
for fruit in ["apple", "banana"]:
    print(fruit)

# range() — generate a sequence of numbers
for i in range(5):          # 0 1 2 3 4
    print(i)

for i in range(2, 10, 2):   # 2 4 6 8 (start, stop, step)
    print(i)

# enumerate() — get index AND value
for i, fruit in enumerate(["apple", "banana"]):
    print(i, fruit)            # 0 apple, 1 banana

# zip() — iterate over two lists together
for name, score in zip(["Alice", "Bob"], [90, 85]):
    print(f"{name}: {score}")

while

i = 0
while i < 5:
    print(i)
    i += 1
Use break to exit a loop early, continue to skip to the next iteration, and pass as a no-op placeholder.

9. Functions

# Basic function
def greet(name):
    return f"Hello, {name}!"

greet("Alice")              # "Hello, Alice!"

# Default parameters
def greet(name="World"):
    return f"Hello, {name}!"

greet()                     # "Hello, World!"

# *args — variable positional arguments
def total(*nums):
    return sum(nums)

total(1, 2, 3, 4)            # 10

# **kwargs — variable keyword arguments
def describe(**info):
    for k, v in info.items():
        print(f"{k}: {v}")

describe(name="Alice", age=30)

# Lambda — anonymous single-expression function
double = lambda x: x * 2
double(5)                    # 10

10. Modules & Imports

# Import a whole module
import math
math.sqrt(16)                # 4.0
math.pi                       # 3.14159…

# Import specific names
from math import sqrt, ceil
sqrt(25)                      # 5.0

# Import with alias
import datetime as dt
dt.date.today()

# Useful standard library modules
import os          # file system, environment variables
import sys         # interpreter info, argv
import json        # parse/write JSON
import re          # regular expressions
import random      # random numbers
import datetime    # dates and times

11. File I/O

# Write to a file
with open("data.txt", "w") as f:
    f.write("Hello, file!\n")

# Read entire file
with open("data.txt", "r") as f:
    contents = f.read()

# Read line by line
with open("data.txt") as f:
    for line in f:
        print(line.strip())

# Append to a file
with open("data.txt", "a") as f:
    f.write("New line\n")
Always use the with statement when working with files — it automatically closes the file even if an error occurs.

12. Intro to OOP

class Animal:
    """A simple Animal class."""

    # Class variable (shared by all instances)
    kingdom = "Animalia"

    def __init__(self, name: str, age: int):
        # Instance variables
        self.name = name
        self.age  = age

    def describe(self) -> str:
        return f"{self.name} is {self.age} years old."

    def __str__(self):
        return self.name


# Inheritance
class Dog(Animal):
    def __init__(self, name, age, breed):
        super().__init__(name, age)  # call parent __init__
        self.breed = breed

    def speak(self) -> str:
        return f"{self.name} says: Woof!"


dog = Dog("Rex", 4, "Labrador")
print(dog.describe())           # Rex is 4 years old.
print(dog.speak())              # Rex says: Woof!
print(Dog.kingdom)              # Animalia
MethodPurpose
__init__Constructor — called when creating an instance
__str__String representation — used by print()
__repr__Developer representation — used in the REPL
__len__Called by len()
__eq__Called by ==