Constants and Literals

► Overview

Constants are values that don’t change during program execution. Literals are fixed values written directly in code. Understanding these helps write clear, maintainable programs.

► Real-World Analogy

Think of constants like universal truths:
» Pi is always 3.14159
» Number of days in a week is always 7
» Speed of light is constant
» These values never change

► Key Concepts

✓ Constant: A value that should not change
✓ Literal: A value written directly in code
✓ Naming Convention: UPPERCASE for constants
✓ Immutability: Cannot be modified after assignment

■ Constants Example

/code

Define constants

PI = 3.14159
MAX_USERS = 100
APP_NAME = “MyApp”

Using constants

radius = 5
area = PI * radius * radius
print(f”Area: {area}”)

Literals examples

age = 25 # Integer literal
price = 99.99 # Float literal
name = “Alice” # String literal
is_active = True # Boolean literal

► Benefits of Constants

✓ Code readability improves significantly
✓ Easy to update values in one place
✓ Prevents accidental value changes
✓ Makes code self-documenting

► Remember

✓ Use UPPERCASE names for constants
✓ Define constants at the top of file
✓ Don’t use magic numbers – create constants
✓ Constants make code more maintainable

■ Practice Challenge

  1. Create constants for days in week, hours in day
  2. Calculate circle circumference using PI constant
  3. Define constants for tax rate and calculate total price