Chapter 2: Data Types & Variables
Understand Python’s built-in types and how to assign and name variables.
Downloadchapter2.py
Objectives
- Identify Python’s core data types:
int,float,str,bool,None. - Declare and name variables following Python conventions.
- Distinguish mutable vs immutable types.
1. Core Data Types
Python has several primitive types:
int: integers, e.g.42float: floating-point numbers, e.g.3.14str: text, e.g."Hello"bool: boolean,TrueorFalseNoneType: absence of value,None
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:
- Lowercase words, underscores to separate:
my_variable. - Must start with letter or underscore, not with a digit.
- Cannot use reserved keywords:
for,class, etc.
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
- Print the type of each literal:
123,3.14,"text",False,None. - Create three variables of different types and print their names and values in one
print()call. - Demonstrate mutating a list and attempting (and failing) to mutate a string.