Area 2.2

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.

2
Core Concepts
6
Type Conversions
~1.5hrs
Study Time

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 value

Constants

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 constants

Variable 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 declaration

Advantages:

  • 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: 25

Fails if string contains non-numeric characters

String to Float

float(string_value)
price = float("19.99") # Result: 19.99

Can 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.0

Safe conversion, no data loss

Float to Integer

int(float_value)
whole = int(3.7) # Result: 3

Truncates decimal part (no rounding)

Boolean Conversion

bool(value)
flag = bool(0) # Result: False

0, empty string, None evaluate to False

Learning Activities

Variable Scope Investigation

Experiment
30 minutes

Experiment with local and global variables to understand scope behavior

Type Conversion Workshop

Practice
40 minutes

Practice converting between different data types and handle conversion errors

Variable Naming Convention Review

Review
20 minutes

Evaluate and improve variable names following Python conventions