2.2 Variables and Constants
Definitions, purpose, and Python examples
Variables
Definition: A variable is a named storage location used to hold a value that can change.
Purpose: To store and manipulate data during program execution.
When used: When values need to change or be reused.
Python example:
Purpose: To store and manipulate data during program execution.
When used: When values need to change or be reused.
Python example:
score = 0
score = score + 10
print(score)
Constants
Definition: A constant is a named value that should not change during program execution.
Purpose: To protect fixed values and improve readability.
When used: For values such as limits, configuration values, or mathematical constants.
Python note: Python does not enforce constants, but uppercase names are used by convention.
Python example:
Purpose: To protect fixed values and improve readability.
When used: For values such as limits, configuration values, or mathematical constants.
Python note: Python does not enforce constants, but uppercase names are used by convention.
Python example:
MAX_USERS = 100
PI = 3.14159
print(MAX_USERS)
print(PI)
Data Type Conversion
Definition: Data type conversion changes a value from one data type to another.
Purpose: To allow compatible operations and handle user input correctly.
Why used: Input is often read as text and must be converted.
Python example:
Purpose: To allow compatible operations and handle user input correctly.
Why used: Input is often read as text and must be converted.
Python example:
age_text = "16"
age = int(age_text)
price = float("9.99")
print(age)
print(price)
Scope
Definition: Scope determines where a variable can be accessed in a program.
Purpose: To manage memory and avoid naming conflicts.
When used: When organising code into functions or modules.
Purpose: To manage memory and avoid naming conflicts.
When used: When organising code into functions or modules.
Global and Local Variables
Global variables: Accessible throughout the program.
Local variables: Only accessible within the function where they are defined.
Python example:
Local variables: Only accessible within the function where they are defined.
Python example:
total = 0 # Global variable
def add_number():
number = 5 # Local variable
return total + number
print(add_number())
Using Variables, Constants and Scope
Variables and constants are declared using standard data types and
used throughout programs to store, calculate, and control logic.
Python example:
Python example:
TAX_RATE = 0.2
price = 50
tax = price * TAX_RATE
total_price = price + tax
print(total_price)