Identifiers are the names used to identify variables, functions, classes, modules, or other objects in Python. They are user-defined names and play a significant role in making the code readable and meaningful.
1. Characteristics of Identifiers:
- Unique Names: They should uniquely represent variables, functions, or objects.
- Case-Sensitive: Python distinguishes between uppercase and lowercase letters. For example, name and Name are different identifiers.
- Must Start with a Letter or Underscore (_): The first character must be an alphabet (A-Z or a-z) or an underscore.
- Cannot Use Special Characters: Identifiers cannot contain symbols like @, #, $, %, etc.
- Can Include Letters, Digits, and Underscores: After the first letter, digits (0-9) can be used.
- Cannot Be a Keyword: Identifiers cannot be the same as Python’s reserved keywords.
2. Rules for Naming Identifiers:
a. Allowed Identifiers:
- Must follow the naming conventions.
- Examples:
age = 25
first_name = “John”
_temp = 100
b. Invalid Identifiers:
- Start with a digit:
1name = “Invalid” # SyntaxError
- Contain special characters:
name@ = “Invalid” # SyntaxError
- Match Python keywords:
def = 10 # SyntaxError
3. Naming Conventions:
Adhering to conventions improves code readability and maintainability.
- Variables and Functions:
- Use lowercase letters.
- Separate words with underscores (snake_case).
student_name = “Alice”
calculate_sum = lambda x, y: x + y
- Constants:
- Use uppercase letters, separated by underscores.
PI = 3.14159
MAX_VALUE = 100
- Classes:
- Use CamelCase.
class Person:
pass
- Private Identifiers:
- Use a single underscore prefix for non-public identifiers.
_private_var = 10
- Special Identifiers:
- Use double underscores for special methods or system-defined names (dunder methods).
def __init__(self):
pass
4. Examples of Identifiers:
Valid Identifiers:
name = “Alice”
_age = 25
total_1 = 100
sum_of_values = 50
Invalid Identifiers:
1name = “Bob” # SyntaxError: cannot start with a digit
total# = 10 # SyntaxError: special character not allowed
for = 15 # SyntaxError: ‘for’ is a keyword
5. Reserved Identifiers:
While identifiers are user-defined, some names are system-defined or reserved for specific functionalities (e.g., __name__, __main__). Avoid using them unless necessary.
6. Best Practices for Identifiers:
- Use meaningful names to describe the purpose of the variable or function.
# Bad
x = 10
# Good
student_age = 10
- Avoid overly long names; keep them concise yet descriptive.
- Stick to one naming convention throughout the project for consistency.
- Avoid single-character names unless in loops (i, j, k).
Conclusion:
Identifiers are the building blocks of Python programming, giving structure and clarity to the code. By adhering to naming conventions and rules, developers can write more readable, maintainable, and error-free programs.