varsity college 2
Variable Assignment
When assigning a value to a variable:
The variable must be on the left-hand side of the operator.
Declaring Constants
Name Constants:
Similar to variables, but they can only be assigned a value once.
Should be assigned a meaningful name corresponding to a value that will not change during the program's execution.
Magic Number:
An unnamed constant that can lead to confusion, thus it's better to use named constants.
Example of Constants
Example given:
num_sales_tax_rate = 0.06
Variable name:
num_sales_tax_rate
(it is a noun)This variable is a constant because it is written in capital letters.
Identical Statements
After declaring
sales_tax_rate
, both statements:tax_amount = price * 0.06
tax_amount = price * sales_tax_rate
These two statements have identical meanings because
sales_tax_rate
represents the constant value of0.06
.Using the constant makes the code cleaner and easier to maintain as it avoids magic numbers.
Identifying Variables
First Variable: Check for validity:
Is it correct? No.
Why? Because it contains a space between words.
Second Variable: Check for validity:
Is it correct? No.
Why? Contains special characters which are not allowed in variable names.
Importance of properly named variables to ensure readability and prevent errors in programming.