TutorChase logo
IB DP Computer Science Study Notes

4.3.6 Understanding Variables, Constants, and Operators

Grasping the concepts of variables, constants, and operators is crucial in the world of programming. These elements enable programmers to define, manipulate, and interact with the data that makes up the core of any software application.

Variables: Definition and Characteristics

  • Definition: In computer programming, a variable is a memory location where a developer can store a data value. Unlike constants, the value in a variable can change or vary throughout the course of program execution.
  • Characteristics:
    • Mutability: A variable’s primary feature is that its value is mutable; it can be changed at runtime.
    • Data Type: Variables can be of different data types such as integers, floats, strings, or booleans. The type determines what kind of values the variable can hold and how much space it takes in memory.
    • Scope: This defines the area of a program where a variable is accessible. For example, a variable declared within a function is not accessible outside that function.
    • Lifetime: Refers to the period during which the variable exists in memory. Variables typically have either local scope (alive only during the function execution) or global scope (alive throughout the program execution).
    • Naming Conventions: It’s crucial to use meaningful variable names. Names should start with a letter and can include numbers and underscores. For example, ‘userAge’, ‘totalCost’, ‘isMember’.

Constants: Definition and Characteristics

  • Definition: Constants are similar to variables but with immutability; once they are assigned a value, it cannot change during the lifetime of the program.
  • Characteristics:
    • Immutability: The key feature of constants is that their value, once defined, cannot be altered. This helps in maintaining values which shouldn’t change, like ‘PI = 3.14159’.
    • Declaration and Initialisation: Constants are generally declared and initialised at the same time. Some programming languages enforce constants to be defined at compile time.
    • Usage: Constants are used to give a descriptive name to otherwise unclear numeric values, enhancing the readability and maintainability of code.

Operators in Programming

Operators in programming are symbols that tell the computer to perform specific mathematical, relational, or logical operations.

Arithmetic Operators

  • Addition (‘+’), Subtraction (‘-’), Multiplication (‘*’), Division (‘/’): These operators are used for basic mathematical operations.
  • Modulus (‘mod‘): This operator returns the remainder of a division operation. For example, ‘5 mod 2’ equals 1.
  • Division (‘div‘): In some programming languages, ‘div‘ indicates integer division where the result is an integer and the remainder is discarded.

Relational Operators

  • Comparisons: Include equals (=), not equals (), less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=). These operators compare two values and return a Boolean result.

Logical Operators

  • AND, OR, NOT: These operators are used to form complex Boolean expressions and are crucial in decision-making structures and loops.

Practical Examples

Using Variables and Constants

  • Example 1: Age Verification System
    • A variable, ‘customerAge’, stores the age input by a customer.
    • Constants, ‘LEGAL_DRINKING_AGE’ and ‘SENIOR_AGE’, might be used to represent legally required age thresholds.
    • The program can then compare ‘customerAge’ with these constants to determine service eligibility.

Utilising Operators

  • Example 2: Discount Calculation
    • Variables like ‘originalPrice’ and ‘discountRate’ can be used to store the price of an item and the discount percentage respectively.
    • An operation such as ‘finalPrice = originalPrice - (originalPrice * discountRate / 100)’ utilises arithmetic operators to calculate the discounted price.

Combining Variables, Constants, and Operators

  • Example 3: Weather Alert System
    • Constants such as ‘MAX_SAFE_TEMPERATURE’ and ‘MIN_SAFE_TEMPERATURE’ might represent temperature thresholds.
    • A variable currentTemperature stores the current temperature reading.
    • The program can use relational operators to check if ‘currentTemperature’ is outside safe limits and trigger an alert if necessary.

By exploring these foundational concepts through practical examples, students can gain a better understanding of how variables, constants, and operators function in real-world programming scenarios. Mastering these concepts is essential for creating effective and efficient algorithms, contributing significantly to the overall success of any programming project.


Operator precedence in programming determines the order in which operators are evaluated in an expression. In expressions with multiple operators, understanding precedence is crucial to ensure that the operators are applied in the intended order, affecting the final result of the expression. For example, in the expression ‘3 + 4 * 5‘, the multiplication is performed before the addition because multiplication has a higher precedence than addition. If the operators were evaluated from left to right without regard to precedence, the result would erroneously be ‘35‘ instead of the correct ‘23‘. Parentheses can be used to override the default precedence if a different order of evaluation is needed. Misunderstanding operator precedence is a common source of bugs in programming, highlighting the importance of either knowing the rules of precedence in your programming language or using parentheses to explicitly state the intended order of operations.

Type coercion refers to the automatic or implicit conversion of values from one data type to another within an expression involving different data types. This can occur in programming when operators are used with variables of different types. For example, in the expression ‘5 + "10"‘, if the programming language automatically converts the integer 5 to a string and performs string concatenation, the result would be the string ‘"510"‘ instead of the mathematical sum ‘15‘. The impact of type coercion is significant as it can lead to unexpected results or bugs, especially in languages where coercion rules might not be immediately clear or intuitive. Understanding how and when your programming language of choice coerces types is crucial for writing clear, effective code, as it influences the outcomes of operations and ensures that the operations behave as intended.

In programming, data types are often categorised as mutable or immutable based on whether instances of these types can be changed after they are created. Immutable data types do not allow the modification of the instance itself once created. For example, in many languages, strings and numbers are immutable. Mutable data types, like lists or dictionaries in Python, allow for their elements to be altered. The choice between mutable and immutable types affects how variables and constants are used. Constants are typically immutable to ensure that their value remains constant throughout the program. Variables can be either mutable or immutable, influencing how they are used. Mutable variables are useful for data that is expected to change, like a counter in a loop, whereas immutable variables can help to ensure data integrity by preventing unintended modifications.

Following naming conventions for variables and constants is vital for several reasons. Firstly, it improves the readability of the code, making it easier for others (and yourself at a later time) to understand what the code does. Good names convey purpose and usage of the variable or constant, reducing the need for additional comments. Secondly, it helps in maintaining consistency throughout the codebase, which is particularly important in collaborative environments or large projects. Some common conventions include using camelCase (e.g., ‘totalCost‘, ‘userAge‘) for variables, and UPPER_CASE (e.g., ‘MAX_HEIGHT‘, ‘DEFAULT_TIMEOUT‘) for constants. Additionally, names should be descriptive and clear, avoiding ambiguous abbreviations and instead opting for names that clearly describe the data they represent, such as using ‘customerEmailAddress‘ over vague terms like ‘data‘ or ‘temp‘.

Local and global variables differ primarily in their scope, which determines where these variables can be accessed and modified within the program. A local variable is declared within a function or block and can only be accessed within that function or block. Its existence is temporary, and it is typically used for temporary calculations within the function. Once the function or block completes its execution, the local variable is destroyed. On the other hand, a global variable is declared outside any function or block, usually at the beginning of the program. It can be accessed and modified by any part of the program, making its scope the entire program. While global variables offer convenience by being universally accessible, they can lead to issues with data integrity and make debugging difficult, as any part of the program can modify them. Local variables, with their limited scope, help in creating more modular and error-resistant code, where changes in one function don’t inadvertently affect another part of the program.

Practice Questions

Given the following pseudo-code, identify the variables, constants, and operators used. Also, explain the purpose of each operator.

In the pseudo-code, ‘MAX_LIMIT’ is a constant and ‘counter’ is a variable. The constant ‘MAX_LIMIT’ is used to set a fixed upper limit for the loop, in this case, 100, which cannot be changed during the execution of the program. The variable ‘counter’ is used to keep track of the number of iterations the loop has completed. The operators used are:

  • ‘<= ‘ (less than or equal to): It's a relational operator that checks whether ‘counter‘ is less than or equal to ‘MAX_LIMIT‘.
  • ‘+‘ (addition): An arithmetic operator that increments the value of ‘counter‘. The purpose of these operators is to control the flow of the loop, ensuring it repeats until the ‘counter‘ reaches ‘MAX_LIMIT‘.
Write a piece of pseudo-code that uses variables, constants, and at least three different operators to calculate and store the area of a circle in a variable, given the radius. Explain the significance of each component used.

In this pseudo-code:

  • ‘PI‘ is a constant representing the value of Pi. Its value is unchangeable, ensuring accuracy in all calculations involving Pi.
  • ‘radius‘ and ‘area‘ are variables. ‘radius‘ stores the length of the circle's radius, and area is used to store the calculated area of the circle.
  • The operators used are:
    • ‘*‘ (multiplication): It multiplies the values together. Here, it's used twice; first to square the radius and then to multiply it by Pi to find the area.
  • The use of constants and variables here makes the code more understandable and allows for easy modifications of the ‘radius‘ value without altering the formula for the area of a circle.
Alfie avatar
Written by: Alfie
Cambridge University - BA Maths

A Cambridge alumnus, Alfie is a qualified teacher, and specialises creating educational materials for Computer Science for high school students.

Hire a tutor

Please fill out the form and we'll find a tutor for you.

1/2 About yourself
Still have questions?
Let's get in touch.