Python Identifiers
What are the Identifiers?
In Python, an identifier is a name used to identify variables, functions, classes, modules, or other objects. It can be composed of letters (both uppercase and lowercase), digits, and underscores. However, there are certain rules and conventions to follow when writing identifiers. Here are the rules for writing Python identifiers:
Rules for writing identifiers.
The first character of an identifier must be a letter (a-z, A-Z) or an underscore (_). It cannot be a digit or any special character.
The remaining characters in the identifier can be letters, digits, or underscores. Special characters such as @, $, and % are not allowed.
Identifiers are case-sensitive, meaning that variables named "myVariable" and "myvariable" would be considered as different identifiers.
Python keywords cannot be used as identifiers. Keywords are reserved words that have special meanings in Python. For example, "if," "while," and "def" are all keywords and cannot be used as identifiers.
Identifiers should be descriptive and meaningful, following the naming conventions recommended by the Python community. It is common to use lowercase letters with words separated by underscores for variable and function names (e.g., my_variable, calculate_area). For class names, the convention is to use CamelCase, where each word starts with an uppercase letter and there are no underscores (e.g., MyClass, CarModel).
Avoid using single underscores at the beginning or end of an identifier (e.g., myvar, myvar). Although it is allowed, this convention is typically used to indicate that a variable or method is intended for internal use within a class or module.
Here are some examples of valid identifiers:
my_variable
calculate_area
CarModel
MAX_COUNT
_name
And here are some examples of invalid identifiers:
2ndNumber # starts with a digit
my-variable # contains a hyphen
if # a reserved keyword
Python Keywords.
Here is a table listing the keywords in Python:
False | await | else | import | pass |
None | break | except | in | raise |
True | class | finally | is | return |
and | continue | for | lambda | try |
as | def | from | nonlocal | while |
assert | del | global | not | with |
async | elif | if | or | yield |
These keywords have special meanings in Python and cannot be used as identifiers for variables, functions, or other objects.
Subscribe to my newsletter
Read articles from Aksh Darji directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by