Skip to content

2.2 Variable naming

When naming variables in Python, there are specific rules and conventions to follow. Adhering to these guidelines helps in writing clear, readable, and maintainable code.

2.2a Rules for variable naming

  1. Starting character - Variable names must start with a letter (a-z, A-Z) or an underscore (_). They cannot start with a number.

  2. Subsequent characters - After the first character, variable names can include letters, numbers (0-9), and underscores.

  3. Case sensitivity - Variable names are case-sensitive. For example, variable, Variable, and VARIABLE are three different variables.

  4. Reserved keywords - You cannot use Python reserved keywords (like if, for, while, class, def, etc.) as variable names. These keywords have special meanings in Python.

 

Example 2.2.1 - Examples of valid variable names

my_variable = 10
_myVariable = 20
MyVariable2 = 30
variable123 = 40
  Example 2.2.2 - Examples of invalid variable names
1variable = 10        # Cannot start with a number
my-variable = 20      # Hyphens are not allowed
class = 30            # 'class' is a reserved keyword

 


 

2.2b Python variable naming conventions

To write code that is easy to read and understand, Python programmers follow certain naming conventions. Here are some widely accepted conventions:

1. Snake case - Use snake_case for variable names. This means using lowercase letters and separating words with underscores. - Example: my_variable, user_age, total_price.

2. Descriptive names - Choose meaningful and descriptive names that make the purpose of the variable clear. - Example: user_age is more descriptive than ua.

3. Constants - Use uppercase letters with underscores separating words for constant variables (variables that should not change). - Example: PI = 3.14159, MAX_SPEED = 120.

4. Avoid single characters - Avoid single-character variable names except for common cases like i, j, k in loops or x, y in mathematical operations. - Example: index is more descriptive than i (unless i is used in a simple loop).

 

Example 2.2.3 - Good naming conventions

user_name = "kim"
total_price = 99.99
number_of_items = 5
is_active = True
PI = 3.14159
MAX_CONNECTIONS = 100

 

Example 2.2.4 - Poor naming conventions

x = "kim"          # Not descriptive
tp = 99.99           # Not descriptive
n = 5                # Not descriptive
a = True             # Not descriptive
pi = 3.14159         # Constants should be uppercase
maxconnections = 100 # Should use underscores

 


 

Exercise 2.2.1 - Write a small Python program by first declaring a variable called first_name and then set (initialize) this variable to your name.

Exercise 2.2.1 - Model Answer - Make sure to work out the exercise before checking the model answer.