Variables and Primitive Types
Learn how to declare variables, understand Python primitive types, and convert between types.
Learning objectives
- Declare variables using snake_case naming conventions
- Identify integers, floats, strings, booleans, and NoneType
- Use type() and type casting functions (int(), float(), str(), bool())
Lesson material
Declaring Variables
A variable is a named container holding a value in memory. In Python, assignment is done with the = operator.
Python Naming Conventions (PEP 8):
- Use
snake_casefor variable and function names. - Variable names must start with a letter or underscore, NOT a number.
- Names are case-sensitive (
agevsAge).
Example code
# Variable declarations
user_name = "Alice" # str
user_age = 25 # int
account_balance = 199.99 # float
is_active = True # bool
middle_name = None # NoneType
print(f"{user_name} is {user_age} years old.")
print("Type of user_age:", type(user_age))
Type Conversion (Casting)
You can convert values between types using built-in constructors:
int("10")->10float("3.14")->3.14str(100)->"100"bool(1)->True(0, "", None, [], {} evaluate to False)
Example code
num_str = "42"
num_int = int(num_str)
print(num_int + 8)
Practice exercise: Variable Math and Casting
Create a variable `age_str` with value `"20"`. Cast it to an integer, add 5 to it, and print the result.
Test yourself with the Module 2: Variables and Data Types quiz →