Values, variables and constants

Reading time5 min

In brief

Article summary

The central concepts of this article are values and variables. A key underlying notion is related to types, which determine possible operations on values. Finally, we mention a more complex type, called an array, which allows to work on collections of values.

Main takeaways

  • Values have an associated type, which defines possible operations on them.

  • Variables are names that refer to values that may change, while constants are names that refer to fixed values.

  • Always favor variables and constants rather than values in your code.

  • Programming languages define several elementary types, such as booleans, integers, real numbers, strings, etc.

  • Data structures allow to group simple types into collections.

Article contents

1 — Values, variables and constants

Algorithms manipulate values such as 34, 1.09, "IMT Atlantique" or false that can be integrated into calculus, as for instance 34 * 1.09 to get the conversion into euros of 34 dollars using a rate of 1.09. In addition to these raw values, algorithms can also manipulate variables and constants. These are names that represent a value stored in memory.

Manipulating such names is far more convenient for programming, and especially for updating codes. Using variables in your algorithm makes it possible to avoid errors and to make your algorithm more explicit.

In more details:

  • A variable associates a value with a name. Values associated to a variable may change during program execution.

  • In some situations, you may want to prevent the value assigned to a variable from being changed. A way to do that is to use constants. Technically, the value is stored in memory and the name of the variable/constant acts as a link to this memory address. In some programming languages, attempting to change the value assigned to a constant will result in an error.

  • Attaching a value to a variable or a constant is called an “assignment”.

Example

Let’s manipulate values, variables and constants in a short example, adapted from the one above:

# Let's set three constants to represent the values 34, 1.09 and 1.5 in memory
# A standard convention is to write constants in capital letters to distinguish them from variables
AMOUNT = 34
RATE = 1.09
FEES = 1.5

# Now, let's define a variable using them
converted_amount = AMOUNT * RATE

# Later, we can update the variable if needed
# For instance, let's charge fees for conversion operations
converted_amount = converted_amount * FEES

# However, we are not supposed to change constants after their definition
# For instance, asjusting fees as follows is a bad practice
# In Python, it will work though, but many other languages will raise an error
FEES = 2
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // Let's set three constants to represent the values 34, 1.09 and 1.5 in memory
        // A standard convention is to write constants in capital letters to distinguish them from variables
        // In Java, we explicitely indicate that these names are constant using keyword "const".
        const int AMOUNT = 34;
        const float RATE = 1.09f;
        const float FEES = 1.5f;

        // Now, let's define a variable using them
        float convertedAmount = AMOUNT * RATE;

        // Later, we can update the variable if needed
        // For instance, let's charge fees for conversion operations
        convertedAmount = convertedAmount * FEES;

        // However, we are not supposed to change constants after their definition
        // For instance, asjusting fees as follows is a bad practice
        // In Java, it will raise an error
        FEES = 2;
    }
}
Important

When using values in your code, if the conversion rate changes, you need to change your algorithm everywhere the value is written.

On the contrary, constants allow to avoid this repetition of values and make it easier to update a code. Therefore, always privilegiate constants rather than values, even if you just write RATE = 1.09 at the beginning of the algorithm.

2 — Basic types

Almost all available programming languages consider that a value, and therefore a variable (or constant), has a type.

The type of a value determines:

  • The space required in memory to store it.
  • The operations that can be applied to it.

Programming languages provide basic types and mechanisms to build your own composite types. Here are the main basic types, that you will find in most programming languages:

  • Integers $\mathbb{Z}$ (e.g., -35, 42, 0).
  • Reals $\mathbb{R}$ (e.g., 3.14, -13.49, $\sqrt{2}$).
  • Booleans (true or false).
  • Characters (e.g., ‘!’, ‘X’, ‘\n’).
  • Strings (e.g., “IMT Atlantique”, “Hello!”, “?!”).
Example

Let’s have a look at some programming languages.

The following example shows that a type is associated to each variable/constant. Contrary to Java, Python does not require the type of a variable/constant to be explictly declared, it is a dynamically typed language. Another difference is that Python does not propose a specific type to manipulate a character. A character is simply a string of length 1.

# Booleans
b = True
print(type(b))

# Integers
i = -35
print(type(i))

# Characters
new_line = '\n'
print(type(new_line))

# Strings
print(type("IMT Atlantique"))

# Result of a computation beetween integers
result = 456 * 10^9
print(type(result))

# Reals
val = -87.56
print(type(val))
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // Booleans
        boolean b = true;
        System.out.println(((Object) b).getClass().getName());

        // Integers
        int i = -35;
        System.out.println(((Object) i).getClass().getName());

        // Characters
        char new_line = '\n';
        System.out.println(((Object) new_line).getClass().getName());

        // Strings
        System.out.println(((Object) "IMT Atlantique").getClass().getName());

        // Result of a computation between integers
        int result = 456 * 10 ^ 9;
        System.out.println(((Object) result).getClass().getName());

        // Reals
        float val = -87.56f;
        System.out.println(((Object) val).getClass().getName());
    }
}

This gives us the following output:

Output
<class 'bool'>
<class 'int'>
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
java.lang.Boolean
java.lang.Integer
java.lang.Character
java.lang.String
java.lang.Integer
java.lang.Float

3 — Operators

3.1 — On numerical values

The type of a value or variable determines the operations that can be applied on it. On numerical values, i.e., integers and reals, arithmetic operators with their classical priorities can be applied:

# Addition
v = 12 + 3.3

# Multiplication
v = 1.5 * 2

# Division and floor division
v = 4.12 / 1.5 // 2

# Exponentiation
v = 3.2 ** 2

# Modulo, rest of the Euclidean division
v = 3762 % 6
// Needed imports
import java.lang.Math;

/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // Addition
        double a = 12 + 3.3;

        // Multiplication
        double m = 1.5 * 2;

        // Division and floor division
        double d = Math.floor(4.12 / 1.5 / 2);

        // Exponentiation
        double e = Math.pow(3.2, 2);

        // Modulo, rest of the Euclidean division
        double mo = 3762 % 6;
    }

}

3.2 — On booleans

Boolean values can be combined using operators from the Boolean algebra: conjunction (and), disjunction (or) and negation (not). The negation operator turns true into false and vice versa. The truth table of the conjunctive and disjunctive operators is given below.

a b a and b a or b
true true true true
true false false true
false true false true
false false false false

The Boolean algebra is a central piece of many algorithmic statements and you will often have to express complex Boolean expressions. De Morgan’s laws are two transposition rules that may be very useful to determine the negation of complex Boolean expressions. Here are these two rules:

  • not(A and B) == not(A) or not(B)
  • not(A or B) == not(A) and not(B)

Comparison operators intervene in the construction of conditions to give a Boolean value. They are the same for Python and Java:

  • == to test the equality and != for inequality.
  • <, >, <=, >= for superior/inferior comparisons.
Important

Do not confuse the assignment operator = with the equality operator ==. The former has the lowest priority and is thus executed once its right side expression has been completely interpreted. Thus, result = 2 == 3 will assign false to variable result.

3.3 — Other simple types

There a many operators defined on other data types. For instance, in many programming languages, operator + can be used to concatenate strings. Similarly, [] can be used to access an element or a substring of a given string.

In general, when you want to make simple operations on a basic data type, there is an operator for it, so don’t hesitate to look the cheatsheet here.

4 — Mutable and immutable types

Related to the idea of changeble or not changeble values, is the concept of “mutability”. Mutability is a property associated with the type of a value, hence the type of a variable/constant.

  • If a variable/constant is associated with a “mutable” value, it means that its content may be changed during code execution.
  • If a variable/constant is associated with an “immutable” value, it means that its content cannot be changed during code execution, and attempts to change it will result in an error or the creation of a new variable to store the new value.

Depending on the programming langage, data types are either mutable or immutable. In Python, for example, lists and dictionaries are mutable, which means that we can change their contents without having to create a new variable. On the contrary, tuples, integers, or strings are immutables. Check each data type for their mutability!

Example

This is why l.append(2) can be written like this instead of new_l = l.append(2) (where l is a list). In fact, the second code will set new_l = None, as append returns nothing.

Also, this is why s.upper() returns a value instead of changing the string s directly.

Important

Keep in mind this notion of mutability, as it will be something very important when studying functions in the dedicated programming session.

To go further

Important

The content of this section is optional. It contains additional material for you to consolidate your understanding of the current topic.

Looks like this section is empty!

Anything you would have liked to see here? Let us know on the Discord server! Maybe we can add it quickly. Otherwise, it will help us improve the course for next year!

To go beyond

Important

The content of this section is very optional. We suggest you directions to explore if you wish to go deeper in the current topic.