Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Python

# Guess the number game
import random


def generate_secret_number(min: int, max: int) -> int:
    return random.randint(min, max)


def main() -> None:
    print("Guess the number!")

    secret_number = generate_secret_number(1, 100)

    while True:
        print("Please input your guess.")

        try:
            guess = int(input())
        except ValueError:
            continue

        print(f"You guessed: {guess}")

        if guess < secret_number:
            print("Too small!")
        elif guess > secret_number:
            print("Too big!")
        else:
            print("You win!")
            break


main()

Types

  • Constants: no built-in constants, use all-caps convention
  • Primitives:
    • Numeric: int, float, complex
    • Sequence: str, list, tuple, range, bytes
    • Mapping: dict
    • Set: set, frozenset
    • Boolean: bool
    • None: type(None) → NoneType
  • Dynamic typing: variables can be reassigned to any type
  • Type hints: name: int = 10 (not enforced at runtime)

Variables

# assignment
x = 10
age: int = 20   # with type hint

# multiple assignment
x, y = 1, 2
a = b = 0
x, y = y, x     # swap

# `del` unbinds a name
del x

# variable names (PEP 8)
snake_case  # functions, variables, attributes
UPPER_CASE  # constants

Operators

  • Arithmetic: +, -, *, / (float), // (floor), % (modulo), ** (power)
  • Relational: ==, !=, <, <=, >, >=
  • Logical: and, or, not
  • Bitwise: &, |, ^, <<, >>
  • Assignment: =, +=, -=, *=, /=, //=, %=, **=
  • Membership: in, not in
  • Identity: is, is not

Branching

# if-elif-else
if condition:
    ...
elif condition:
    ...
else:
    ...

# ternary expression
value = a if condition else b

# there is no switch-case, use `match` (Python 3.10+)

Pattern Matching (match)

match command:
    case "quit":
        ...
    case "move" as action:  # binding
        ...
    case ["go", direction]:   # sequence pattern
        ...
    case {"key": value}:      # mapping pattern
        ...
    case Point(x=0, y=0):     # class pattern
        ...
    case 1 | 2 | 3:           # or pattern
        ...
    case _:                   # wildcard (default)
        ...

Looping

# while loop
while condition:
    ...

# for loop (iterates over sequence/iterator)
for item in iterable:
    ...

# range
range(5)         # 0, 1, 2, 3, 4
range(2, 5)      # 2, 3, 4
range(0, 9, 2)   # 0, 2, 4, 6, 8
range(6, 0, -1)  # 6, 5, 4, 3, 2, 1

# break and continue
for i in range(10):
    if condition: break
    if condition: continue

# for-else: else runs only when no break occurs
for item in iterable:
    if is_target(item):
        break
else:  # executed when the loop ends without `break`
    print("not found")

Functions

# definition
def greet(name: str = "World") -> str:
    return f"Hello, {name}!"

# call
greet()
greet("Saplyn")

# keyword arguments
def point(x, y): ...
point(x=1, y=2)

# variadic arguments
def f(*args, **kwargs):
    print(args)    # tuple
    print(kwargs)  # dict
f(1, 2, a=3, b=4)

# lambda (anonymous function)
add = lambda a, b: a + b
add(1, 2)  # 3

Collections

List (mutable, ordered)

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

fruits[0]           # "apple"
fruits[-1]          # "cherry" (negative index)
fruits[1:3]         # ["banana", "cherry"] (slice)

fruits.append("kiwi")
fruits.remove("banana")
fruits.pop()        # remove and return last item

len(fruits)         # length
"apple" in fruits   # membership

Tuple (immutable, ordered)

t = (1, 2, 3)   # can omit: t = 1, 2, 3
t[0]            # 1
# t[0] = 99 would raise TypeError
# destructuring
a, b, c = t

Dict (key-value)

d = {"name": "Saplyn", "age": 20}

d["name"]            # access by key
d["height"] = 180    # add / update
d = dict(name="Saplyn", age=20)  # another construction

d.get("weight", 0)   # returns 0 if missing
"name" in d          # key membership
d.keys()
d.values()
d.items()

# iteration
for key in d:
    print(key)
for key, value in d.items():
    print(key, value)

Set

s = {1, 2, 3}

s.add(4)
s.remove(2)      # raise KeyError if missing
s.discard(9)     # no error if missing
s.union(other)
s.intersection(other)
s.difference(other)

String Operations

s = "Hello, World!"

len(s)          # length
s.upper()       # "HELLO, WORLD!"
s.lower()       # "hello, world!"
s.split(",")    # ["Hello", " World!"]
s.strip()       # remove leading/trailing whitespace
s.replace("World", "Python")

# f-string formatting
name, age = "Saplyn", 20
f"Hi {name}, you are {age}."   # "Hi Saplyn, you are 20."

# slicing
s[7:]  # "World!"
s[::-1] # "!dlroW ,olleH" (reverse)

# contains
"World" in s