In Python, an identifier is a name given to a variable, function, class, or module. It is used to identify the entity in the program.
An identifier can contain letters (both uppercase and lowercase), numbers, and underscore (_). However, it cannot start with a number. Here are some rules for naming an identifier in Python:
- An identifier must begin with a letter or an underscore (_).
- An identifier cannot start with a number.
- An identifier can only contain alphanumeric characters (letters and numbers) and underscores (_).
- Identifiers are case-sensitive, meaning that “myVar” and “myvar” are two different identifiers.
- Python has some reserved words that cannot be used as an identifier. These reserved words include keywords like “if,” “else,” “for,” “while,” and “class.”
Examples of valid identifiers in Python:
my_var = 10
myVar = 20
_myvar = 30
myVar123 = 40
Examples of invalid identifiers in Python:
1myvar = 10 # Cannot start with a number
my-var = 20 # Cannot contain a hyphen
my var = 30 # Cannot contain a space
if = 40 # Cannot use a reserved keyword as an identifier