Variables and Constants
Learn how to store and manage data using variables and constants. Understand scope, type conversion, and naming conventions for effective data management in programs.
Learning Objectives
- Understand the difference between variables and constants
- Apply variable declaration and initialization techniques
- Distinguish between local and global scope
- Use constants for immutable values appropriately
- Perform type conversion and casting operations
- Follow proper naming conventions for variables and constants
Variables vs Constants
Variables
Storage locations that can change value during program execution
Characteristics:
- Mutable (can change)
- Must be declared
- Can be reassigned
- Have data types
Best Practices:
- Use descriptive names (age, not a)
- Initialize variables before use
- Use snake_case for Python variables
- Keep variable scope as narrow as possible
Python Example:
# Variable declaration and initialization
name = "Alice" # String variable
age = 25 # Integer variable
height = 5.6 # Float variable
is_student = True # Boolean variable
# Variables can change
age = 26 # Reassigning new value
name = "Bob" # Changing string valueConstants
Values that remain unchanged throughout program execution
Characteristics:
- Immutable (cannot change)
- Set once at declaration
- Often use UPPER_CASE names
- Improve code readability
Best Practices:
- Use ALL_CAPS for constant names
- Place constants at top of file/module
- Use constants for magic numbers
- Group related constants together
Python Example:
# Constants (by convention in Python)
PI = 3.14159 # Mathematical constant
MAX_USERS = 100 # System limit
DEFAULT_COLOR = "purple" # Configuration value
TAX_RATE = 0.08 # Business rule
# Constants should not be changed
# PI = 3.14 # Bad practice - don't change constantsVariable Scope
Local Scope
Variables declared inside functions, accessible only within that function
def calculate_area(radius):
pi = 3.14159 # Local variable
area = pi * radius * radius
return area
# pi is not accessible here - would cause error
# print(pi) # NameError!Advantages:
- Prevents naming conflicts
- Memory efficient
- Easier to debug
- Promotes encapsulation
Best Used For:
Function parameters, temporary calculations, loop counters
Global Scope
Variables declared at module level, accessible throughout the entire program
counter = 0 # Global variable
MAX_ATTEMPTS = 3 # Global constant
def increment_counter():
global counter # Declare intent to modify global
counter += 1
def get_counter():
return counter # Can read global without declarationAdvantages:
- Accessible everywhere
- Persistent across function calls
- Good for configuration
Best Used For:
Program configuration, shared counters, application state
Type Conversion & Casting
String to Integer
int(string_value)age = int("25") # Result: 25Fails if string contains non-numeric characters
String to Float
float(string_value)price = float("19.99") # Result: 19.99Can handle decimal points in strings
Number to String
str(number_value)text = str(42) # Result: "42"Always safe, any number can become string
Integer to Float
float(integer_value)decimal = float(5) # Result: 5.0Safe conversion, no data loss
Float to Integer
int(float_value)whole = int(3.7) # Result: 3Truncates decimal part (no rounding)
Boolean Conversion
bool(value)flag = bool(0) # Result: False0, empty string, None evaluate to False
Learning Activities
Variable Scope Investigation
Experiment with local and global variables to understand scope behavior
Type Conversion Workshop
Practice converting between different data types and handle conversion errors
Variable Naming Convention Review
Evaluate and improve variable names following Python conventions