Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
In Python, an identifier is a name used to identify variables, functions, classes, modules, or other objects. Following a consistent naming convention makes your code more readable and maintainable. Python's recommended naming conventions are defined in PEP 8, the Python style guide.
Here are the general rules for creating identifiers:
my_variable
and My_Variable
are considered different identifiers.Here are the naming conventions for different types of identifiers:
Variables and functions: Use lowercase letters and separate words with underscores (snake_case). Example: my_variable
, calculate_sum
Constants: Use uppercase letters and separate words with underscores. Example: PI
, MAX_SIZE
Classes: Use PascalCase, capitalizing the first letter of each word. Example: MyClass
, DataProcessor
Modules: Use short, lowercase names, and separate words with underscores if necessary. Example: my_module
, file_reader
Instance attributes and methods: Use lowercase letters and separate words with underscores (snake_case). Example: self.my_attribute
, self.my_method()
Private attributes and methods: Prefix the identifier with a single underscore. Example: self._private_attribute
, self._private_method()
"Strongly private" attributes and methods: Prefix the identifier with two underscores. This triggers Python's name mangling, which makes it more difficult to accidentally access or modify the attribute or method. Example: self.__strongly_private_attribute
, self.__strongly_private_method()
Magic methods and attributes: Use double underscores as a prefix and suffix. Example: __init__
, __str__
, __call__
Remember, these are conventions, not strict rules. However, following them will make your code more consistent and easier to read for others who are familiar with Python's naming conventions. When working with existing projects, follow the project's existing conventions for consistency.
Python Variable Naming Conventions:
# Example: my_variable = 42
Naming Conventions for Python Functions:
# Example: def calculate_sum(a, b): return a + b
CamelCase vs snake_case in Python:
# Snake case my_variable_name = 10 # Camel case (commonly used for class names) class MyClass: pass
Python Class Naming Conventions:
# Example: class Car: def __init__(self, make, model): self.make = make self.model = model
How to Name Variables in Python:
# Example: user_age = 25
Python Module Naming Conventions:
# Example: import mymodule
Consistent Naming in Python Code:
# Consistent naming example: def process_data(data_list): for item in data_list: print(item)