Constants
A constant is a name for a value that is fixed when the program is written and stays the same for the whole run. It works like a variable because you refer to it by name to reach a stored value, but the programmer treats the value as fixed: it is set once and is not given a new value while the program runs.
You give the constant its value with = when you write the program, and afterwards you use it just like a variable: wherever the name appears, it stands for the stored value. If the value needs to be different, the programmer edits that line of code and runs the program again. Constants are a programming technique used in high-level languages such as Python.
A helpful way to picture it is a label on a fixed value: the program can read through the label, but what sits under the label stays put for the whole run.
A school library lets each pupil borrow the same number of books at a time, and that number is fixed by the librarian. The program below stores the limit as a constant and uses its name to work out how many more books a pupil may take out.
BORROW_LIMIT = 4
books_taken = int(input("How many books have you taken out? "))
books_left = BORROW_LIMIT - books_taken
print("You may still borrow", books_left, "books.")Output when the user types 1:
How many books have you taken out? 1
You may still borrow 3 books.
The line BORROW_LIMIT = 4 sets the constant once. The program reads the value through the name BORROW_LIMIT when it works out books_left, but it never gives the name a new value. If the school changes its rule to five books, you edit that one line and run the program again โ you do not change it while the program is running.
OCR GCSE Computer Science ยท Constants