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:
Python
JavaScript
Java
C++
const PI = 3.14159;
console.log(PI);Why Use Constants?
Using constants makes your code easier to understand and maintain:
- Readability: Names like
PIorDAYS_IN_WEEKexplain 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.
Python
JavaScript
Java
C++
const PI = 3.14159;
PI = 3; // Error: Assignment to constant variableNote: 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.
No comments:
Post a Comment