Identifier
- An identifier is a unique name given to variables, functions, classes, etc., for identification in Python.
-
Identifiers are created using a combination of letters (A-Z, a-z), digits (0-9), and underscores (
_
). - They cannot start with a digit
-
It doesn't allow special characters like
@
,#
, or% except (_) underscore
.
- Keywords (35 in Python 3.10) cannot be used as identifiers.
-
Python identifiers are case-sensitive, meaning
VarName
andvarname
are treated differently.
-
The
.isidentifier()
method checks if a string is a valid identifier, returningTrue
orFalse
.
# Valid Identifiers:
variable1 = 10 # Starts with a letter and contains numbers.
_temp_var = 20 # Starts with an underscore (allowed, but use carefully).
myFunction = 30 # Combines letters in camel case (common convention).
value123 = 40 # Contains letters and numbers but starts with a letter.
MAX_VALUE = 60 # Uses all uppercase letters and underscores (common for constants).
# invalid identifiers
1variable = 11 # Starts with a number (invalid).
my-var = 22 # Contains a hyphen, which is not allowed.
@temp = 24 # Uses a special character (@), which is invalid.
def = 26 # A Python keyword, so it cannot be used as an identifier.
hello world = 11 # Contains a space, which is not allowed.
# Validation Example Using .isidentifier():
print("variable1".isidentifier()) # True
print("1variable".isidentifier()) # False
print("my-var".isidentifier()) # False
print("_valid".isidentifier()) # True