Variables & constants

Reading time5 min

In brief

Article summary

In this article, we present you the notions of constants and variables. We also introduce you to the notion of 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

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

  • Always favor variables over constants.

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

  • 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 — Variables and constants

Algorithms manipulate values that may be constants or variables.

Values such as 34, 1.09, “IMT Atlantique” or false are constants 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.

Important

If the conversion rate changes, you need to change your algorithm everywhere the constant is used. Therefore, always privilegiate variables rather than constants, even if you just write rate = 1.09 at the beginning of the algorithm.

Variables make it possible to avoid such situations and to make your algorithm more explicit.

A variable is the association of a constant with a name. At a given execution time of your algorithm, the variable possesses a value, but this value can be changed. Technically, the constant is stored in memory and the name of the variable acts as a link to this memory address. Attaching a constant to a variable is called an “assignment”.

Example

For instance, we can define three variables to reproduce the case above:

amount = 34
rate = 1.09
converted_amount = amount * rate
/**
 * 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) {
        int amount = 34;
        float rate = 1.09f;
        float convertedAmount = amount * rate;
    }
}

2 — Basic types

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

The type of a constant determines:

  • The space required in memory to store the value.
  • 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 constant and variable. Contrary to Java, Python does not require the type of a variable 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.

b = True
print(type(b))

i = -35
print(type(i))

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

print(type("IMT Atlantique"))

result = 456 * 10^9
print(type(result))

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) {
        boolean b = true;
        System.out.println(((Object) b).getClass().getName());

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

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

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

        int result = 456 * 10 ^ 9;
        System.out.println(((Object) result).getClass().getName());

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

This gives us the following 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 constant 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
/**
 * 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.
 */

import java.lang.Math;

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 make a quick online search.

4 — (Static) data structures

Basic data types seen previously allows to assign a single value to a variable. Many different data structures make it possible to regroup and structure several values behind a single variable. Whereas a session is dedicated to dynamic data structures, we will introduce here a static data structure called array.

An array is a data type that can store a collection of values of a same type and of a predefined size.

An array (say T), has a length, say N, and each value is associated with an index from 0 (its first element) to N - 1 (the last value). The notation T[i] is generally used to access the values of index i in T.

Information

Some languages choose to number elements from 1 to N. However the standard case (including Python and Java) is to start counting from 0.

Let’s illustrate array manipulation with an example:

# Declaration of an array of integers
T = [1, -5, 85, -55, 0, 1]

# Assign the third values of T in variable v3
v3 = T[2]

# Print the length of T
print("Length of T =" , len(T))
/**
 * 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) {
        // Declaration of an array of integers
        int[] T = {1, -5, 85, -55, 0, 1};

        // Assign the third values of T in variable v3
        int v3 = T[2];

        // Print the length of T
        System.out.println("Length of T = " + T.length);
    }
}
Information

Python does not make the distinction between lists and arrays. This makes their usage more flexible, as they can be extended and contain various data types. However, if you need a fixed-size array, you can use a numpy.ndarray or a torch.tensor type. Check the numpy documentation and the torch documentation for their usage.

5 — Mutable and immutable variables

A variable associates a name with a value stored in main memory. This value has a type that can be “mutable” or “immutable”.

When a variable is associated with a mutable value, it means that its content may be changed after during code execution. On the contrary, an immutable value cannot be changed once assigned to a variable.

In Python, lists and dictionaries are mutable, which means that we can change their contents without havint 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.

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.

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.