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// Copyright (c) 2020 Mr. Coxall All rights reserved.
2//
3// Created by: Mr. Coxall
4// Created on: Sep 2020
5// This program shows declaring constants
6
7#include <stdio.h>
8
9int main() {
10 // constant definition
11 const int ROOM_NUMBER = 212;
12 const float HST = 0.13;
13 const char COUNTRY[6] = "Canada";
14
15 printf("Room: %d\n", ROOM_NUMBER);
16 printf("HST %.2f%%\n", HST);
17 printf("%s\n", COUNTRY);
18
19 printf("\nDone.\n");
20 return 0;
21}
1// Copyright (c) 2020 Mr. Coxall All rights reserved.
2//
3// Created by: Mr. Coxall
4// Created on: Sep 2020
5// This program shows declaring constants
6
7#include <iostream>
8
9int main() {
10 // constant definition
11 const int ROOM_NUMBER = 212;
12 const float HST = 0.13;
13 const std::string COUNTRY = "Canada";
14
15 std::cout << "Room: " << ROOM_NUMBER << std::endl;
16 std::cout << HST << "%" << std::endl;
17 std::cout << COUNTRY << std::endl;
18
19 std::cout << "\nDone." << std::endl;
20}
1/* Created by: Mr. Coxall
2 * Created on: Sep 2020
3 * This program shows declaring constants
4*/
5
6using System;
7
8/*
9 * The Program class
10 * Contains all methods for performing basic constants usage
11*/
12class Program {
13 public static void Main (string[] args) {
14 // constant definition
15 const int ROOM_NUMBER = 212;
16 const float HST = 0.13f;
17 const string COUNTRY = "Canada";
18
19 Console.WriteLine("Room: " + ROOM_NUMBER);
20 Console.WriteLine(HST + "%");
21 Console.WriteLine(COUNTRY);
22
23 Console.WriteLine("\nDone.");
24 }
25}
1/**
2 * Created by: Mr. Coxall
3 * Created on: Sep 2020
4 * This program shows declaring constants
5 */
6
7package main
8
9import "fmt"
10
11func main() {
12 // constant definition, Go does not use ALL CAPS
13 const room int = 212
14 const hst float64 = 0.13
15 const country string = "Canada"
16
17 fmt.Println("Room:", room)
18 fmt.Println(hst*100, "%")
19 fmt.Println(country)
20
21 fmt.Println("\nDone.")
22}
1/*
2 * This program shows declaring constants
3 *
4 * @author Mr Coxall
5 * @version 1.0
6 * @since 2020-09-01
7 */
8
9final class Main {
10 private Main() {
11 // Prevent instantiation
12 // Optional: throw an exception e.g. AssertionError
13 // if this ever *is* called
14 throw new IllegalStateException("Cannot be instantiated");
15 }
16
17 /** Constant number of lives. */
18 private static final int ROOM = 212;
19
20 /** Constant for HST. */
21 private static final double HST = 0.13;
22
23 /** Constant for COUNTRY. */
24 private static final String COUNTRY = "Canada";
25
26 /**
27 * Main entry point into program.
28 *
29 * @param args nothing passed in
30 */
31 public static void main(final String[] args) {
32 // output
33 System.out.println("Room: " + ROOM);
34 System.out.println(HST + "%");
35 System.out.println(COUNTRY);
36
37 System.out.println("\nDone.");
38 }
39}
1/**
2* Created by: Mr. Coxall
3* Created on: Sep 2020
4* This program shows declaring constants
5*/
6
7// constant definition
8const ROOM = 212
9const HST = 0.13
10const COUNTRY = "Canada"
11
12console.log("Room: " + ROOM)
13console.log(HST + "%")
14console.log(COUNTRY)
15
16console.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#!/usr/bin/env python3
2"""
3Created by: Mr. Coxall
4Created on: Sep 2020
5This module holds constants
6"""
7
8# constant definition
9ROOM_NUMBER = 212
10HST = 0.13
11COUNTRY = "Canada"
main.py
1#!/usr/bin/env python3
2"""
3Created by: Mr. Coxall
4Created on: Sep 2020
5This module shows declaring constants
6"""
7
8import constants
9
10
11def main() -> None:
12 """The main() function shows declaring constants, returns None."""
13 print("Room: " + str(constants.ROOM_NUMBER))
14 print(str(constants.HST) + "%")
15 print(constants.COUNTRY)
16
17 print("\nDone.")
18
19
20if __name__ == "__main__":
21 main()
Example Output
