What are Identifiers?
Identifiers
are names used to label variables, functions, classes, modules, and other objects in a program.
Note: An object refers to anything that includes data and the behavior (methods) related to this data. In Python, everything is an object.
Python Identifier Rules
-
Starting Character Rule
: An identifier must start with a letter (A-Z, a-z) or an underscore (_). It cannot start with a digit. -
Use of Characters, Digits, Underscore
: After the first character, it can be followed by letters, digits (0-9), or underscores (_). -
Reserved Keywords Cannot Be Used
: Words like def and if, which are reserved for specific language functions, cannot be used as identifiers. -
Case Sensitivity
: Python identifiers are case-sensitive.myname
andmyName
are considered different identifiers.
# Valid identifier examples
my_variable = 10 # Variable name starts with a letter or underscore
def my_function(): # Function name starts with a letter or underscore
print("Hello")
class MyClass: # Class name starts with a letter or underscore
pass
# Invalid identifier examples
2my_variable = 10 # Variable name cannot start with a digit
def if(): # 'if' keyword cannot be used as a function name
Importance of Identifiers
Identifiers like variable, function, and class names should be descriptive and reflect their purpose in the code.
radius = 25 # Variable name representing the radius
def calculate_circle_area(radius): # Function name to calculate circle area
return 3.14 * radius * radius
Coding Practice
Try entering the highlighted 1_my_number = 7
on the practice screen.
You'll see an error occurs when a variable name starts with a digit.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.