Chapter 2: Data Types & Variables

Understand Python’s built-in types and how to assign and name variables.

Download chapter2.py

Objectives

1. Core Data Types

Python has several primitive types:

Use type() to inspect:

>>> type(100)
<class 'int'>
>>> type("Python")
<class 'str'>

2. Variables & Naming

Assign values with =:

x = 10
name = "Alice"
is_valid = True

Naming rules:

Reassign any variable to new types freely:

x = 10
x = "ten"     # now a str

3. Mutability vs Immutability

Immutable types (int, float, str, tuple) cannot be changed in place.

Mutable types (list, dict, set) can be modified:

# Immutable
a = "hello"
a += " world"   # creates new string

# Mutable
lst = [1, 2, 3]
lst.append(4)   # modifies same list object

Exercises

  1. Print the type of each literal: 123, 3.14, "text", False, None.
  2. Create three variables of different types and print their names and values in one print() call.
  3. Demonstrate mutating a list and attempting (and failing) to mutate a string.