This chapter covers the building blocks of every Python program: values, types, operators, and the core collection types.

Variables and Assignment

Variables are names that refer to objects in memory:

  x = 42
name = "Alice"
price = 19.99
is_active = True

# Multiple assignment
a, b, c = 1, 2, 3
x, y = y, x  # swap values
  

Python is dynamically typed — you don’t declare types, but values always have a type:

  type(42)        # <class 'int'>
type("hello")   # <class 'str'>
type(3.14)      # <class 'float'>
type(True)      # <class 'bool'>
  

Numeric Types

  # Integers — unlimited precision
big = 10 ** 100

# Floats — IEEE 754 double precision
pi = 3.14159
scientific = 1.5e-4  # 0.00015

# Complex numbers
z = 3 + 4j
  

Numeric Operations

  10 + 3    # 13
10 - 3    # 7
10 * 3    # 30
10 / 3    # 3.3333...  (float division)
10 // 3   # 3          (floor division)
10 % 3    # 1          (modulo)
2 ** 8    # 256        (exponent)
divmod(10, 3)  # (3, 1)  quotient and remainder
  

Strings

  s1 = 'single quotes'
s2 = "double quotes"
s3 = """Multi-line
strings work too"""

# Concatenation and repetition
greeting = "Hello" + " " + "World"
line = "-" * 40
  

String Methods

  text = "  Hello, Python!  "

text.strip()           # "Hello, Python!"
text.lower()           # "  hello, python!  "
text.upper()           # "  HELLO, PYTHON!  "
text.replace("Python", "World")
"hello world".split()  # ['hello', 'world']
"-".join(["a", "b"])   # "a-b"
"Python".startswith("Py")  # True
"123".isdigit()        # True
  

String Formatting

  name, score = "Alice", 95.5

# f-strings (preferred, Python 3.6+)
f"{name} scored {score:.1f}%"

# format method
"{} scored {:.1f}%".format(name, score)
  

Indexing and Slicing

  word = "Python"
word[0]      # 'P'
word[-1]     # 'n'
word[0:3]    # 'Pyt'
word[::-1]   # 'nohtyP'
  

Booleans and Truthiness

  True and False   # False
True or False    # True
not True         # False

# Truthy: non-zero numbers, non-empty collections, non-None
# Falsy: 0, 0.0, "", [], {}, set(), None, False
bool("")     # False
bool("hi")   # True
bool(0)      # False
bool([])     # False
bool([1])    # True
  

Operators

  # Comparison
5 == 5    # True
5 != 3    # True
5 > 3     # True
5 >= 5    # True

# Chained comparisons
1 < x < 10

# Identity (same object in memory)
a is b
a is not b

# Membership
"x" in "hello"
3 in [1, 2, 3]
  

Collections Overview

Lists

  nums = [1, 2, 3]
nums.append(4)
nums[0] = 10
len(nums)
  

Tuples

  coords = (10, 20)
x, y = coords  # unpacking
  

Dictionaries

  person = {"name": "Bob", "age": 25}
person["name"]
person.get("email", "unknown")
  

Sets

  unique = {1, 2, 3, 2}  # {1, 2, 3}
unique.add(4)
  

See Data Structures Deep Dive for comprehensive coverage.

Input and Output

  name = input("Enter your name: ")
age = int(input("Enter your age: "))

print("Name:", name)
print(f"Next year you'll be {age + 1}")

# Formatted output
print(f"{'Name':<10} {'Age':>5}")
print(f"{name:<10} {age:>5}")
  

Type Conversion

  int("42")       # 42
float("3.14")   # 3.14
str(100)        # "100"
bool(1)         # True
list("abc")     # ['a', 'b', 'c']
  

These fundamentals appear in every Python program. Next up: Data Structures and Control Flow.