Variable Names

Variable names in Python are used to store data values for later use in your program. Choosing meaningful and descriptive variable names is important for writing readable and maintainable code. In this lesson, we will cover the rules and conventions for naming variables in Python.

Rules for Variable Names

Variable names in Python must adhere to the following rules:

  • Must start with a letter (a-z, A-Z) or underscore (_).
  • Can contain letters, numbers, and underscores.
  • Cannot contain spaces or special characters (e.g., !, @, #, $, %).
  • Cannot be a Python keyword (e.g., if, else, for).

Conventions for Variable Names

It is recommended to follow certain conventions when naming variables in Python to make your code more readable:

  • Use descriptive names that indicate the purpose of the variable (e.g.,total_score instead of ts).
  • Use lowercase letters for variable names, and separate words with underscores for readability (e.g., user_name).
  • Avoid using single-letter variable names except for simple iterators (e.g.,i, j).

Example

# Valid variable names
my_var = 42
user_name = 'Alice'
total_score = 100

# Invalid variable names
2nd_place = 2
total-score = 95
for = 'loop'

Conclusion

Choosing appropriate variable names is crucial for writing clean and understandable code. By following the rules and conventions for naming variables in Python, you can improve the readability and maintainability of your code.



[ Footer Placeholder]