In Python, keywords and identifiers are fundamental elements that play a crucial role in how Python programs are written and executed. Understanding the rules governing keywords and identifiers will help you write clear, effective, and error-free Python code.
This guide explains what keywords and identifiers are, the rules for their usage, and best practices for naming variables and functions.
In Python, keywords are reserved words that have special meanings and are used to define the syntax and structure of the Python language. These words cannot be used as variable names, function names, or identifiers because they are reserved for specific language features.
For example, if
, else
, for
, while
, class
, and def
are all keywords in Python. Keywords are essential for writing Python programs, as they define control flow, data structures, and other language constructs.
Python keywords are case-sensitive, meaning that True
is a keyword, but true
is not.
As of Python 3, here is the complete list of keywords:
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
True
, False
, None
if
, else
, elif
, for
, while
, break
, continue
, pass
, return
, raise
, try
, except
, finally
def
, lambda
, yield
except
, finally
import
, from
, global
, nonlocal
, assert
, del
, is
, in
, and
, or
, not
, with
To check the current list of Python keywords in your version of Python, you can use the keyword
module:
import keyword
print(keyword.kwlist)
Identifiers are names used to identify variables, functions, classes, modules, and other objects in Python. Identifiers allow you to give meaningful names to different elements in your program, making your code easier to understand and maintain.
In Python, an identifier is any name that meets the following criteria:
_
).class
, return
, for
, etc.).myVariable
and myvariable
would be considered two different identifiers.Here are the key rules for naming identifiers in Python:
First Character: The first character of an identifier must be a letter (uppercase or lowercase) or an underscore (_
). It cannot be a number.
myVar
, _temp
, X1
1var
, #temp
Subsequent Characters: After the first character, the identifier can contain letters, digits, and underscores.
my_var
, temp123
my@var
, var#1
Cannot Be a Keyword: You cannot use Python keywords as identifiers (e.g., for
, while
, class
, def
, etc.).
def = 5
, for = 10
Case Sensitivity: Python identifiers are case-sensitive, meaning that myVar
, myvar
, and MYVAR
are all different identifiers.
var
, Var
, VAR
Length: Python identifiers can be of any length, but they should be meaningful and concise. Long identifiers can make the code harder to read.
counter
, i
Underscores: You can use underscores (_
) in identifiers, commonly to indicate private variables or methods in classes.
my_variable
, _privateVar
, __specialVar
Choosing good, descriptive names for your identifiers is important to make your code easy to read and maintain. Here are some best practices:
Use Descriptive Names: Choose names that describe the purpose or use of the variable, function, or class. Avoid single-letter names (except in short loops or mathematical formulas).
customer_age
, calculate_total
a
, temp
Use Snake Case for Variables and Functions: In Python, it is common practice to use snake_case for variable and function names, where words are separated by underscores.
total_cost
, get_user_input
Use CamelCase for Classes: By convention, class names in Python should be written in CamelCase (also called PascalCase), where each word starts with a capital letter and no underscores are used.
UserProfile
, DataProcessor
Use Leading Underscore for Private Variables: To indicate that a variable or method is intended for internal use (private), you can prefix it with a single underscore.
_internal_count
Avoid Using Single Leading and Trailing Underscores: Avoid using identifiers like _var_
unless they are reserved for special methods, such as __init__
(the constructor) or __str__
(string representation). These are often called "dunder" methods.
Keep It Readable: The most important aspect of naming identifiers is making your code easy to read and understand. Use spaces or underscores to separate words if necessary.
calculate_total_price
is more readable than calculateTotalPrice
.Using Keywords as Identifiers: This is a syntax error and can cause your program to fail.
class = "hello"
(incorrect)Confusing Case Sensitivity: Since Python is case-sensitive, make sure you don't confuse myVar
and myvar
. These will be treated as two separate identifiers.
myVar
and myvar
are different.Starting Identifiers with Numbers: Identifiers cannot start with a number.
123abc = 5
(incorrect)Overusing Underscores: While underscores can help make identifiers more readable, too many underscores in a name can be excessive and hard to read.
___temp___
is not necessary unless it's required for special cases.Short, Meaningless Identifiers: Avoid using single-letter or overly short names unless they are common conventions or are used in specific contexts (e.g., loop variables).
x
, y
, z
are fine for mathematical formulas, but not for general-purpose variables.