Identifiers
In python, Identifiers are the names given to any variable, function, class, object or module.
These names are given by programers. Identifiers are used to uniquely identify these in our code.
Rules to define Identifiers :
- Identifiers can only contain letters (a-z, A-Z), digits (0-9), and underscores (_).
- Identifiers must not start with a digit.
- Identifiers are case-sensitive (`myVar` and `myvar` are different).
- And we cannot use reserved words / keywords as indentifiers.
- There is no length limit for Python identifiers. But not recommended to use too lengthy identifiers.
- We must use descriptive and meaningful names for better code readability.
Example :
name = "Alice"
_age = 25
total_amount1 = 100.50
In the above Example, there is no output. But here 'name', '_age' and 'total_amount1' are identifiers. These are valid identifiers.
Question : Find the valid identifiers from below list.
- cash = 10
- cash$ = 15
- all!hands = 30
- total123 = 100
- 123total = 100
- if = 33
- _abc_abc_ = 22
- def = 44
Answer :
cash = 10 #It is a valid Identifier
cash$ = 15 #Invalid because '$'is not allowed as valid identifier
all!hands = 30 #Invalid because '!'is not allowed as valid identifier
total123 = 100 #Valid
123total = 100 #Invalid because Indentifier must not start with a digit
if = 33 #Invalid because we can not use keyword (if) as Identifier
_abc_abc_ = 22 #Valid
def = 44 #Invalid because we can not use keyword (def) as Identifier
Usage of Identifier :
- Assign values to variables: `age = 25`
- Define functions: `def calculate_sum():`
- Name classes: `class Student:`
- Reference modules and objects
Best Practices :
- Use descriptive and meaningful names (e.g., `total_price` instead of `tp`).
- Use lowercase letters for variable and function names (e.g., `student_name`).
- Use uppercase letters for constants (e.g., `PI = 3.14`).
- Use underscores to separate words in identifiers (`snake_case`).
- Avoid using single-character names except for counters or iterators.
- Never use Python reserved keywords as identifiers.
Comments
Post a Comment