Variables & Types
Introduction
Variables are containers that store values. In Python, they are dynamically typed, meaning you don't have to declare their type explicitly — the interpreter figures it out at runtime. This is similar to JavaScript but with different syntax and conventions. Python variables can hold primitive values (such as numbers and strings) or references to objects (such as lists, dictionaries, functions, or user-defined objects).
In Python, variable assignment is straightforward — you simply use the assignment operator =. Python follows the PEP 8 style guide, which recommends using snake_case for variable names.
Python's type system includes:
- Built-in Types: int, float, str, bool, None, list, tuple, dict, set
- User-defined Types: classes and custom objects
Built-in Types:
- int → integers of arbitrary precision.
- float → floating-point numbers (double precision).
- str → text values (Unicode strings).
- bool → True or False.
- None → Python's null value, similar to null/undefined in other languages.
- list → ordered, mutable collections.
- tuple → ordered, immutable collections.
- dict → key-value pairs (like JavaScript objects).
- set → unordered collections of unique elements.
Type Checking
- Use
type()function to get the exact type of a variable. - Use
isinstance()to check if a variable is of a specific type. - Python's duck typing: "If it walks like a duck and quacks like a duck, it's a duck."
Concepts
Declaring Variables
age = 25
name = "Alice"
is_student = True
salary = None
Type Checking
print(type("Hello")) # <class 'str'>
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
print(isinstance(42, int)) # True
Multiple Assignment
x, y, z = 1, 2, 3
a = b = c = 0
Examples
age = 30
name = "Alice"
is_student = True
salary = None
height = 5.8
big_number = 123456789012345678901234567890
print(type(age)) # <class 'int'>
print(type(name)) # <class 'str'>
print(type(is_student)) # <class 'bool'>
print(type(salary)) # <class 'NoneType'>
print(type(height)) # <class 'float'>
print(type(big_number)) # <class 'int'>
person = {"first_name": "Bob", "last_name": "Smith"}
numbers = [1, 2, 3]
print(type(person)) # <class 'dict'>
print(type(numbers)) # <class 'list'>
# Python supports arbitrary precision integers
huge_number = 2 ** 1000
print(f"Very large number: {huge_number}")
print(f"Type: {type(huge_number)}")
Challenges
1. Variable Declaration
- Declare variables for your first_name, last_name, age, and is_graduate.
- Print each variable with its type.
💡 Show Answer
first_name = "Alice"
last_name = "Smith"
age = 25
is_graduate = True
print(f"Name: {first_name}, Type: {type(first_name)}")
print(f"Last Name: {last_name}, Type: {type(last_name)}")
print(f"Age: {age}, Type: {type(age)}")
print(f"Graduate: {is_graduate}, Type: {type(is_graduate)}")
2. Reassignment
- Create a variable and reassign it to different types.
- Observe how Python handles dynamic typing.
💡 Show Answer
x = 10
print(f"x = {x}, type = {type(x)}")
x = "Hello"
print(f"x = {x}, type = {type(x)}")
x = [1, 2, 3]
print(f"x = {x}, type = {type(x)}")
x = True
print(f"x = {x}, type = {type(x)}")
3. None vs undefined
- Declare a variable assigned to None and explore its properties.
💡 Show Answer
salary = None
print(f"salary: {salary}")
print(f"type: {type(salary)}")
print(f"is None: {salary is None}")
print(f"bool value: {bool(salary)}") # False
4. Large numbers
- Create variables holding very large numbers.
- Demonstrate Python's arbitrary precision integers.
💡 Show Answer
big = 2 ** 100
huge = 10 ** 100
factorial_100 = 1
for i in range(1, 101):
factorial_100 *= i
print(f"2^100 = {big}")
print(f"10^100 = {huge}")
print(f"100! = {factorial_100}")
print(f"All are type: {type(big)}")
5. isinstance vs type
- Demonstrate the difference between isinstance() and type().
- Show how isinstance() works with inheritance.
💡 Show Answer
x = 42
print(f"type(x) == int: {type(x) == int}")
print(f"isinstance(x, int): {isinstance(x, int)}")
# isinstance works with inheritance
print(f"isinstance(True, bool): {isinstance(True, bool)}")
print(f"isinstance(True, int): {isinstance(True, int)}") # True! bool inherits from int
# Check multiple types
y = "hello"
print(f"isinstance(y, (int, str)): {isinstance(y, (int, str))}")
6. Collections
- Create examples of list, tuple, dict, and set.
- Show their types and basic properties.
💡 Show Answer
my_list = [1, 2, 3, 2]
my_tuple = (1, 2, 3, 2)
my_dict = {"name": "Alice", "age": 25}
my_set = {1, 2, 3, 2} # Duplicates removed
print(f"List: {my_list}, Type: {type(my_list)}")
print(f"Tuple: {my_tuple}, Type: {type(my_tuple)}")
print(f"Dict: {my_dict}, Type: {type(my_dict)}")
print(f"Set: {my_set}, Type: {type(my_set)}")
print(f"List length: {len(my_list)}")
print(f"Set length: {len(my_set)}") # 3, not 4!
7. describe_type function
- Write a function describe_type(value) that takes any value and prints "The type of [value] is [type]".
💡 Show Answer
def describe_type(value):
print(f"The type of {value} is {type(value).__name__}")
describe_type("hello")
describe_type(42)
describe_type(True)
describe_type({})
describe_type(None)
describe_type([1, 2, 3])
8. Truthiness
- Show how Python treats different values in boolean contexts.
💡 Show Answer
# Falsy values in Python
print(f"bool(None): {bool(None)}") # False
print(f"bool(0): {bool(0)}") # False
print(f"bool(''): {bool('')}") # False
print(f"bool([]): {bool([])}") # False
print(f"bool({{}}): {bool({})}") # False
# Truthy values
print(f"bool('hello'): {bool('hello')}") # True
print(f"bool(1): {bool(1)}") # True
print(f"bool([1]): {bool([1])}") # True
print(f"bool(-1): {bool(-1)}") # True
9. Type conversion
- Explore type conversion: int(), float(), str(), bool().
💡 Show Answer
# String to number
print(f"int('42'): {int('42')}")
print(f"float('3.14'): {float('3.14')}")
# Number to string
print(f"str(42): '{str(42)}'")
print(f"str(3.14): '{str(3.14)}'")
# Boolean conversion
print(f"bool(0): {bool(0)}")
print(f"bool(1): {bool(1)}")
print(f"int(True): {int(True)}")
print(f"int(False): {int(False)}")
# List to tuple and vice versa
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
back_to_list = list(my_tuple)
print(f"List to tuple: {my_tuple}")
print(f"Tuple to list: {back_to_list}")
10. Variable naming conventions
- Demonstrate Python's naming conventions (PEP 8).
💡 Show Answer
# Good Python variable names (snake_case)
first_name = "Alice"
user_age = 25
is_logged_in = True
MAX_SIZE = 100 # Constants in UPPER_CASE
# Valid but not recommended
firstName = "Bob" # camelCase (not Python style)
UserAge = 30 # PascalCase (for classes)
# Invalid names (would cause SyntaxError)
# 2name = "Invalid" # Can't start with number
# first-name = "Invalid" # Hyphens not allowed
# class = "Invalid" # Can't use Python keywords
print(f"Good naming: {first_name}, {user_age}, {is_logged_in}")
print(f"Constant: {MAX_SIZE}")