Python Identifiers
In Python, identifiers are names used to identify variables, functions, classes, modules, or other objects. An identifier is a sequence of letters, digits, and underscores that must follow certain rules to be valid. Here's how you can define and use identifiers in Python:
Rules for Python Identifiers:
- They can only start with a letter (a-z, A-Z) or an underscore (_).
- The rest of the identifier can contain letters, digits (0-9), and underscores.
- Identifiers are case-sensitive, meaning
myVar
andmyvar
are treated as different identifiers. - Keywords (reserved words like
if
,else
,while
, etc.) cannot be used as identifiers. - Here's an example using identifiers for
name
,age
, andsex
:
Example 1: Variable
my_variable = 42
Explanation:
In this example, my_variable
is an identifier used to represent a variable. It follows the convention of using lowercase letters and underscores for variable names. This makes the code more readable and adheres to the Python naming convention known as "snake_case."
Example 2: Function
def calculate_area(length, width):
return length * width
Explanation:
calculate_area
is an identifier for a function. It follows the same naming convention as variables, using lowercase letters and underscores. Meaningful function names like this one improve code readability and understanding.
Example 3: Class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Explanation:
In this example, Person
is an identifier for a class. Python class names usually follow the convention of using "CamelCase" where each word starts with an uppercase letter. It helps distinguish classes from functions and variables.
Example 4: Module Name
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Explanation:
math_operations
is an identifier for a Python module. Modules are files containing Python code, and naming them with lowercase letters and underscores is a common practice. The .py
extension indicates that it's a Python file.
Example 5: Constant Name
PI = 3.14159265359
Explanation:
PI
is an identifier used to represent a constant. In Python, constants are typically named using uppercase letters with underscores, adhering to the convention that indicates these values should not be changed during program execution.
Remember that using meaningful and descriptive identifiers can make your code more readable and maintainable. It's a good practice to use lowercase names for variables and function names, and uppercase names for constants. Following these conventions enhances the clarity of your code.
Read More : https://www.codinguru.online/python/python-keywords