Python Variables : Variable Names
In Python, variable names must follow certain rules and conventions to be valid and meaningful. Here’s a breakdown:
1. Rules for Variable Names:
- Must start with a letter or an underscore (
_): The first character of a variable name can only be a letter (uppercase or lowercase) or an underscore. - Cannot start with a number: Variable names cannot begin with a digit.
- Can only contain alphanumeric characters and underscores: Variable names can consist of letters, numbers, and underscores (e.g.,
variable_1or_temp_var). - Case-sensitive: Variable names are case-sensitive, meaning
myVarandmyvarwould be two different variables. - No spaces allowed: Spaces are not allowed in variable names; instead, underscores are used to separate words (e.g.,
my_variable). - Cannot be a Python keyword: Variable names cannot be reserved Python keywords like
if,else,while,for,class, etc.
2. Conventions for Variable Names (PEP 8 Style Guide):
- Use meaningful names: Variable names should reflect the content or purpose (e.g.,
student_nameortotal_cost). - Use snake_case: For most variables, Python follows the snake_case convention, where words are all lowercase and separated by underscores (e.g.,
max_value,item_count). - Use UPPERCASE for constants: Variables that are meant to be constants are usually written in all uppercase (e.g.,
PI,MAX_SPEED). - Avoid starting variable names with underscores unless necessary: Single underscores (
_var) can indicate a variable is meant for internal use, while double underscores (__var) can be used for name-mangling (typically in class attributes).
Examples:
# Valid variable names
name = "Alice"
_age = 25
total_items = 10
max_speed = 120
# Invalid variable names
2nd_variable = 5 # Starts with a number
my-variable = 100 # Contains a hyphen
class = "Python" # Uses a reserved keyword