Curriculum
In Python, variable names must follow specific rules to ensure that the code is valid, readable, and maintainable.
Choosing good variable names improves code clarity and makes it easier for others (and yourself) to understand your programs.
This lesson supplements the last lesson (2.1) and provides more information on how to define and use variables.
By the end of this lesson, you will be able to write well-structured and professional-looking code!
Python has a few strict naming rules that must be followed when creating variables.
Variable names must start with a letter (A-Z or a-z) or an underscore (_).
After the first character, variables can contain letters, numbers (0-9), and underscores (_).
Variable names are case-sensitive. (myVar, MYVAR, and myvar are different.)
Variable names cannot be Python reserved keywords. (if, class, return, while, etc.)
Python will raise an error if these rules are not followed.
| Invalid Variable Name | Error Reason |
|---|---|
2name = "Alice" |
Cannot start with a number |
student-name = "Bob" |
Cannot contain hyphens (-); use underscores (_) instead |
class = "Python" |
class is a reserved keyword |
my variable = 10 |
Spaces are not allowed; use my_variable |
name = "Alice" # Starts with a letter
_age = 25 # Starts with an underscore
student_name = "Bob" # Uses underscores
score123 = 98 # Contains numbers (but doesn't start with one)
These names follow Python’s naming rules and will work without errors.
Following consistent naming conventions makes your code more readable and professional.
Good variable names describe their purpose clearly.
Bad Naming (Too Generic or Confusing)
x = "Alice" # What does x represent?
y = 25 # Unclear meaning
Good Naming (Descriptive and Meaningful)
user_name = "Alice" # Clearly represents a user's name
user_age = 25 # Clearly represents the user's age
snake_case)Python follows the snake_case convention: words are separated by underscores (_).
Preferred (Snake Case)
first_name = "Alice"
total_score = 95
user_email = "alice@email.com"
Avoid Camel Case (Used in Java/JavaScript)
firstName = "Alice" # Not Pythonic
totalScore = 95 # Not Pythonic
Avoid Pascal Case (These are used for class names in Python)
FirstName = "Alice" # Not used for variables
TotalScore = 95
As is done in most high-level languages, use Pascal Case only for Class Names in Python, NOT for variables.
A constant is a variable whose value should not change.
Python doesn’t have built-in constants, but by convention, constants are written in uppercase.
PI = 3.14159 # Constant value
MAX_USERS = 1000
DATABASE_URL = "https://example.com"
Note: Python does not enforce constants, so PI = 3.14 will not cause an error, but it is bad practice to change a constant.
_var)In Python, a leading underscore (_variable) indicates a variable is intended for internal use (private).
_private_variable = "This is private"
This is not enforced by Python, but it signals to other programmers that the variable should not be modified externally.
__var) for Name Mangling in ClassesIf a variable has two leading underscores (__var), Python applies name mangling (useful in object-oriented programming).
Name mangling is automatically applied by the Python interpreter to any attribute name that starts with two or more leading underscores and does not end with two or more trailing underscores (e.g., __attribute).
When the Python code is compiled, the interpreter rewrites the attribute name from:
__attribute_name
to:
_ClassName__attribute_name
where ClassName is the name of the class where the attribute is defined.
Example
If you define a variable __secret_value inside a class named Example, the interpreter changes its internal name to _Example__secret_value.
class Example:
def __init__(self):
self.__secret_value = 42 # Private variable with name mangling
obj = Example()
print(obj.__secret_value) # This will raise an AttributeError
Best Practice: Use double underscores only in classes, not for regular variables.
Python reserved keywords have special meanings and cannot be used as variable names.
List of Python Reserved Keywords
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Example of Incorrect Usage
if = 10 # SyntaxError: invalid syntax
return = "Hello" # SyntaxError: invalid syntax
Instead, use:
if_value = 10
return_message = "Hello"
Best Practice: If you accidentally use a keyword, modify the name slightly.
Using prefixes makes it easier to identify variable types.
Examples of Recommended Naming Prefixes
| Variable Type | Example Naming |
|---|---|
| String | user_name, city_name |
| Integer | total_count, num_students |
| Boolean | is_logged_in, has_permission |
| List | user_list, scores_list |
| Dictionary | user_data, config_dict |
Example of Consistent Naming:
is_admin = True # Boolean variable
user_list = ["Alice", "Bob", "Charlie"] # List variable
config_dict = {"theme": "dark", "language": "English"} # Dictionary variable
The application of these best practises makes reading and debugging code easier.
Here is a summary of important concepts that we have covered in this section:
user_name), NOT camelCase (userName)PI = 3.14)_private_var)is_active, user_list)By following these conventions, your Python code will be more readable, maintainable, and professional.
In the next lesson, we will explore data types, such as strings, integers, floats, and booleans – the building blocks of Python programming!
Not a member yet? Register now
Are you a member? Login now