Python Variable Names: A Comprehensive Guide

Python Variable Names: A Comprehensive Guide

In Python, variable names are fundamental for storing data values. This guide will cover the rules for naming variables, techniques for readability, and practical examples.

Table of Contents

Variable Names

A variable can have a short name (like x and y) or a more descriptive name (like age, carName, totalVolume). Choosing clear names is crucial for code readability.

Rules for Naming Variables

Here are the essential rules for naming variables in Python:

  • A variable name must start with a letter or an underscore (_).
  • A variable name cannot start with a number.
  • A variable name can only contain alphanumeric characters and underscores (A-Z, 0-9, and _).
  • Variable names are case-sensitive (age, Age, and AGE are different variables).
  • A variable name cannot be a Python keyword.

Examples of Legal Variable Names:


myvar = "Alice"
my_var = "Alice"
_my_var = "Alice"
myVar = "Alice"
MYVAR = "Alice"
myvar2 = "Alice"

Examples of Illegal Variable Names:


2myvar = "Alice"  # Starts with a number
my-var = "Alice"  # Contains a hyphen
my var = "Alice"  # Contains a space

Multi-Word Variable Names

Variable names with multiple words can be challenging to read. Here are some techniques to improve readability:

Camel Case

Each word after the first starts with a capital letter:


myVariableName = "Alice"

Pascal Case

Each word starts with a capital letter:


MyVariableName = "Alice"

Snake Case

Each word is separated by an underscore:


my_variable_name = "Alice"

Exercise

Which is NOT a legal variable name?

  • my-var = 20
  • my_var = 20
  • Myvar = 20
  • _myvar = 20

Conclusion

Understanding how to name variables correctly is crucial in Python programming. By following the naming rules and using techniques to enhance readability, you will write cleaner and more maintainable code.