Python
About Lesson

Identifiers are names given to entities like variables, functions, classes, etc., in Python. They help in differentiating one entity from another.

Rules for Naming Identifiers:

  1. Start with a letter or an underscore (_): Identifiers must begin with an uppercase or lowercase letter (A-Z, a-z) or an underscore (_).

  2. Followed by letters, digits, or underscores: After the first character, you can use letters, digits (0-9), or underscores.

  3. Case-sensitive: Identifiers in Python are case-sensitive. For example, Variable and variable would be treated as two different identifiers.

  4. No reserved words: You cannot use Python’s reserved keywords (like class, return, if, etc.) as identifiers.

 

Examples of Valid Identifiers:

variable1
_variable
Var123
my_function

 

Examples of Invalid Identifiers:

1variable # Starts with a digit
my-variable # Contains a hyphen
class # Python keyword
def # Python keyword

 

Good Practices for Naming Identifiers:

  • Use meaningful names to make your code more readable.
  • For variables and functions, use lowercase words separated by underscores (snake_case).
  • For classes, use CapitalizedWords (CamelCase).

 

Examples

Let’s look at some examples to see how identifiers are used in Python:

Variables

# Valid identifiers
user_age = 25
_user_name = "Alice"
itemCount = 10
is_valid = True

# Using identifiers in operations
total_items = itemCount + 5
print(total_items) # Output: 15

 

Functions

# Valid function identifier
def calculate_sum(a, b):
return a + b

# Using the function
result = calculate_sum(10, 5)
print(result) # Output: 15

 

Constants

By convention, constants are usually written in all uppercase letters.

# Valid constant identifier
PI = 3.14159
MAX_SPEED = 120

# Using constants
print(PI) # Output: 3.14159
print(MAX_SPEED) # Output: 120

 

Identifiers are crucial in Python programming for naming variables, functions, classes, and other entities. Following the naming rules and conventions helps in writing clear and maintainable code. Always choose meaningful names to make your code self-explanatory.