Chapter 2

Variables & Types

2.0 Intro · 2.1 Variables · 2.2 Operators · 2.3 Types · 2.4–2.6 Built-ins & Collections

← → or Space to navigate · F for fullscreen

2.1 Variables

Assignment, naming conventions, and dynamic typing

Variables & Assignment

  • A variable is a name bound to a value.
  • Assignment uses = (not equality).
  • Python is dynamically typed — the type is inferred from the value.
  • Multiple assignment and swapping are concise.
x = 42           # int
name = "Alice"   # str
pi = 3.14159     # float
active = True    # bool

# Multiple assignment
a, b, c = 1, 2, 3

# Swap without a temp variable
a, b = b, a

# Augmented assignment
x += 10   # same as x = x + 10

2.2 Operators

Arithmetic, comparison, logical, and assignment operators

Operators

Arithmetic

Op Meaning Example
+ - * / Basic 5 / 22.5
// Floor division 5 // 22
% Modulus 5 % 21
** Exponent 2 ** 8256

Comparison

==, !=, <, >, <=, >= → returns True/False

Logical

x = 5
print(x > 0 and x < 10)  # True
print(x < 0 or x > 3)    # True
print(not x == 5)         # False

Short-circuit evaluation

and stops at the first False.
or stops at the first True.

data = None
result = data or []   # [] if data is falsy

2.3–2.5 Built-in Types

Numbers, strings, booleans, and type conversion

Numeric Types

Type Example Notes
int 42, -7 Unlimited precision
float 3.14, 1e-6 IEEE 754 double
complex 2+3j j for imaginary unit
print(type(42))      # <class 'int'>
print(type(3.14))    # <class 'float'>
print(10 / 3)        # 3.3333...
print(10 // 3)       # 3

Type Conversion

int("42")        # 42
float("3.14")    # 3.14
str(100)         # '100'
bool(0)          # False
bool("hello")    # True

0, "", [], {}, None are all falsy. Everything else is truthy.

Strings

  • Immutable sequences of Unicode characters.
  • Single, double, or triple quotes.
  • Indexing (s[0]) and slicing (s[1:4]).
  • Rich method library: .upper(), .split(), .strip(), .replace(), …
s = "Hello, World!"
print(s[0])        # H
print(s[-1])       # !
print(s[7:12])     # World
print(s.lower())   # hello, world!
print(s.split(",")) # ['Hello', ' World!']
print(len(s))      # 13

2.6 Collection Types — Overview

Type Ordered Mutable Unique Access
list index
tuple index
dict ✓ (insertion) keys only key
set membership
nums   = [1, 2, 3]           # list
point  = (3.0, 4.0)          # tuple
person = {"name": "Alice"}   # dict
unique = {1, 2, 3}           # set

Chapter 2 — Quick Reference

Concept Key syntax / notes
Variable x = value — dynamic typing
Augmented assign x += 1, x *= 2
Floor division // integer quotient; % remainder
Exponent 2 ** 10 → 1024
Type check type(x), isinstance(x, int)
Conversion int(), float(), str(), bool()
Falsy values 0, "", [], {}, None
String methods .upper(), .split(), .strip(), .replace()

End of Chapter 2

Next: Chapter 3 — Control Flow

if · elif · else · for · while · break · continue