1.6. Naming Variables#
It is important you give your variables appropriate names - like how you might label boxes at home. If you don’t choose descriptive variable names, it can be very difficult for yourself or others to read your code. This will become increasingly important as you write longer and more complex programs.
Below are two examples of code that calculates the cost of 4 pens and 2 highlighters. Which is easier to interpret?
Program 1
a = 2.89
b = 1.97
c = 4 * a + 2 * b
print(c)
Program 2
pen = 2.89
highlighter = 1.97
cost = 4 * pen + 2 * highlighter
print(cost)
In addition to using descriptive names, there are rules that you must follow when choosing a variable name. A variable name:
Must start with a letter or an underscore character
Can only contain alpha-numeric characters and underscores
Further, variable names are case sensitive. This means that age
and
Age
, are not the same.
age = 32
Age = 17
print(age)
print(Age)
Finally, you must ensure you don’t name your variables using keywords. Keywords are special words in Python that have a special meaning. You will notice that often they will be formatted in a different colour. For example, print is a keyword. If you end up assigning a value to a keyword, you will overwrite it and your code won’t work properly.
print = "hello"
print(print)
Question 1
Which of the following code snippets are valid? Select all that apply.
number
deg2rad
10th
float
ten%
Solution
number
Valid.
deg2rad
Valid. Numbers are allowed as long as they are not at the start of the variable name.
10th
Invalid. Variables must start with a letter or an underscore character.
float
Invalid. Technically this works, but should not be done since float is a keyword in Python.
10%
Invalid. Variables can only contain alpha-numeric characters (a-z, A-Z, 0-9) and underscores.
Question 2
What do you think the output of the following code will be?
new_years = '1st January'
print(New_years)
1st January
New_years
new_years
It will result in an error
Solution
Solution is locked