Constants

There are times in a computer program where you have a value that you need the computer to save that does not change or changes very rarely. Some examples are the value of π (3.14…) and the HST (the HST in Ontario is currently 13%, but it has changed once). When you have values like these, you do not want them to be saved as a variable (since they do not vary or change) but you place them in a constant.

Constants just like variables hold a particular value in memory for a programmer that will be used in the program. The difference is that the computer will not let the programmer change the value of a constant during the running of the program. This prevents errors from happening if the programmer accidently tries to change the value of a constant. It should always be declared, just as a variable is declared to warn the computer and people reading your code that it exists. Constants should be declared right before variables, so that they are prominent and easy to notice. Here are some examples of declaring constants:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program shows declaring constants

#include <stdio.h>

int main() {
    // constant definition
    const int ROOM_NUMBER = 212;
    const float HST = 0.13;
    const char COUNTRY[6] = "Canada";

    printf("Room: %d\n", ROOM_NUMBER);
    printf("HST %.2f%%\n", HST);
    printf("%s\n", COUNTRY);

    printf("\nDone.\n");
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program shows declaring constants

#include <iostream>

int main() {
    // constant definition
    const int ROOM_NUMBER = 212;
    const float HST = 0.13;
    const std::string COUNTRY = "Canada";

    std::cout << "Room: " << ROOM_NUMBER << std::endl;
    std::cout << HST << "%" << std::endl;
    std::cout << COUNTRY << std::endl;

    std::cout << "\nDone." << std::endl;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program shows declaring constants
*/

using System;

/*
 * The Program class
 * Contains all methods for performing basic constants usage
*/
class Program {
    public static void Main (string[] args) {
        // constant definition
        const int ROOM_NUMBER = 212;
        const float HST = 0.13f;
        const string COUNTRY = "Canada";

        Console.WriteLine("Room: " + ROOM_NUMBER);
        Console.WriteLine(HST + "%");
        Console.WriteLine(COUNTRY);

        Console.WriteLine("\nDone.");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program shows declaring constants
 */

package main

import "fmt"

func main() {
	// constant definition, Go does not use ALL CAPS
	const room int = 212
	const hst float64 = 0.13
	const country string = "Canada"

	fmt.Println("Room:", room)
	fmt.Println(hst*100, "%")
	fmt.Println(country)

	fmt.Println("\nDone.")
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
 * This program shows declaring constants
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

final class Main {
  private Main() {
    // Prevent instantiation
    // Optional: throw an exception e.g. AssertionError
    // if this ever *is* called
    throw new IllegalStateException("Cannot be instantiated");
  }

  /** Constant number of lives. */
  private static final int ROOM = 212;

  /** Constant for HST. */
  private static final double HST = 0.13;

  /** Constant for COUNTRY. */
  private static final String COUNTRY = "Canada";

  /**
   * Main entry point into program.
   *
   * @param args nothing passed in
   */
  public static void main(final String[] args) {
    // output
    System.out.println("Room: " + ROOM);
    System.out.println(HST + "%");
    System.out.println(COUNTRY);

    System.out.println("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
/**
* Created by: Mr. Coxall
* Created on: Sep 2020
* This program shows declaring constants
*/

// constant definition
const ROOM = 212
const HST = 0.13
const COUNTRY = "Canada"

console.log("Room: " + ROOM)
console.log(HST + "%")
console.log(COUNTRY)

console.log("\nDone.")

In Python we normally create a seperate file called constants.py and place all our constants in it. This is so that we can import the constants into our main.py file. This is a good way to organize your code and keep it clean.

constants.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module holds constants
"""

# constant definition
ROOM_NUMBER = 212
HST = 0.13
COUNTRY = "Canada"

main.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module shows declaring constants
"""

import constants


def main() -> None:
    """The main() function shows declaring constants, returns None."""
    print("Room: " + str(constants.ROOM_NUMBER))
    print(str(constants.HST) + "%")
    print(constants.COUNTRY)

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output