bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Programming/Programming Concepts
Programming•Programming Concepts

Constants in Programming

What is a Constant?

A constant is a value that cannot be changed after it is assigned.

Constants are useful when you have a value that should stay the same while the program runs, like the value of PI , the number of days in a week, or a fixed URL.

Unlike variables, which can be updated, constants keep the same value once they are created:

Runnable example

PI = 3.14159
print(PI)

Why Use Constants?

Using constants makes your code easier to understand and maintain:

  • Readability: Names like PI or DAYS_IN_WEEK explain what the number means.
  • Safety: Constants protect important values from being accidentally changed.
  • Easy updates: If you need to change a constant (like a tax rate), you only update it in one place.

Changing a Constant

Once a constant is assigned, trying to change it will usually cause an error or be ignored, depending on the language.

Runnable example

PI = 3.14159
PI = 3   # This works in Python, but it is not recommended
print(PI)

Note

In Python, there is no built-in way to make a variable constant. The common practice is to write constant names in UPPERCASE to show other programmers that the value should not change.

Constants in Practice

Here are some common examples of constants:

  • PI = 3.14159 (The mathematical constant pi)
  • DAYS_IN_WEEK = 7
  • URL = "https://example.com"
DAYS_IN_WEEK = 7
print("A week has", DAYS_IN_WEEK, "days")
const DAYS_IN_WEEK = 7;
console.log("A week has " + DAYS_IN_WEEK + " days");
final int DAYS_IN_WEEK = 7;
System.out.println("A week has " + DAYS_IN_WEEK + " days");
const int DAYS_IN_WEEK = 7;
cout << "A week has " << DAYS_IN_WEEK << " days";

Previous

Variables in Programming

Next

If Statements in Programming

This chapter

Overview
25

Lessons

105m

Read time

1. Understanding The Concepts of Programming2. What is Programming ?3. Variables in Programming4. Constants in Programming5. If Statements in Programming6. Arrays in Programming7. Loops in Programming8. Functions in Programming9. Recursion in Programming10. Scope in Programming11. Strings in Programming12. Data Types in Programming13. Type Casting in Programming14. Operators in Programming15. Arithmetic Operators in Programming16. Assignment Operators in Programming17. Comparison Operators in Programming18. Logical Operators in Programming19. Bitwise Operators in Programming20. Comments in Programming21. Input and Output in Programming22. Bits and Bytes in Programming23. Binary Numbers in Programming24. Hexadecimal Numbers in Programming25. Boolean Algebra

On this page

What is a Constant?Why Use Constants?Changing a ConstantConstants in Practice