Python keywords are reserved words that have a special meaning associated with them and can’t be used for anything but those specific purposes.
What is keyword in Python?
Python keywords are reserved words that have a special meaning associated with them and can’t be used for anything but those specific purposes. Each keyword is designed to achieve specific functionality.
Python keywords are case-sensitive.
- All keywords contain only letters (no special symbols)
- Except for three keywords (
True
,False
,None
), all keywords have lower case letters
Get the List of Keywords
As of Python 3.9.6, there are 36 keywords available. This number can vary slightly over time.
We can use the following two ways to get the list of keywords in Python
- keyword module: The keyword is the buil-in module to get the list of keywords. Also, this module allows a Python program to determine if a string is a keyword.
help()
function: Apart from a keyword module, we can use thehelp()
function to get the list of keywords
Example: keyword module
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
All the keywords except, True
, False
, and None
, must be written in a lowercase alphabet symbol.
Example 2: The help()
function
help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False break for not
None class from or
True continue global pass
__peg_parser__ def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
Understand Any keyword
The python help()
function is used to display the documentation of modules, functions, classes, keywords.
Pass the keyword name to the help()
function to get to know how to use it. The help()
function returns the description of a keyword along with an example.
Let’s understand how to use the if
keyword.
print(help('if'))
The "if" statement
******************
The "if" statement is used for conditional execution:
if_stmt ::= "if" assignment_expression ":" suite
("elif" assignment_expression ":" suite)*
["else" ":" suite]
It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section Boolean operations
for the definition of true and false); then that suite is executed
(and no other part of the "if" statement is executed or evaluated).
If all expressions are false, the suite of the "else" clause, if
present, is executed.
Usually, IDE should identify the keywords in a specific colour, and you should take note of that. In the example above, note how the keyword (if, elif, and else) were all identified with the same colour.
Keyword Module
Python keyword module allows a Python program to determine if a string is a keyword.
iskeyword(x)
: Returns True
if x
is a keyword
Example if
is a keyword…
import keyword
print(keyword.iskeyword('if'))
print(keyword.iskeyword('range'))
As you can see in the output, it returned True because ‘if’
is the keyword, and it returned False because the range
is not a keyword (it is a built-in function).
Also, keyword module provides following functions to identify keywords.
keyword.kwlist:
It return a sequence containing all the keywords defined for the interpreter.keyword.issoftkeyword(s)
: ReturnTrue
if s is a Python soft keyword. New in version 3.9keyword.softkwlist
: Sequence containing all the soft keywords defined for the interpreter. New in version 3.9
Types of Keywords
Python 3.10+ has 35 official keywords, but the categorization of keywords can indeed be expanded into specific usage contexts for clarity:
- Value Keywords: These represent built-in values.
- Keywords:
True
,False
,None
- Logical Operator Keywords: Keywords used for logical operations.
- Keywords:
and
,or
,not
,is
,in
- Conditional Keywords: Keywords for conditionals and conditional structures.
- Keywords:
if
,elif
,else
- Loop and Flow Control Keywords: For defining and controlling loops and flow within loops.
- Keywords:
for
,while
,break
,continue
,else
- Function and Class Definition Keywords: For defining functions, classes, context managers, and lightweight functions.
- Keywords:
def
,class
,lambda
- Context Management Keywords: For managing resources (often in I/O operations).
- Keywords:
with
,as
,pass
- Import Keywords: Keywords for module importing and aliasing.
- Keywords:
import
,from
,as
- Return Keywords: For returning values or generator functionality.
- Keywords:
return
,yield
- Exception Handling Keywords: Keywords for handling exceptions and enforcing conditions.
- Keywords:
try
,except
,raise
,finally
,else
,assert
- Variable Scope and Memory Management Keywords: Keywords for managing variable scope and memory.
- Keywords:
del
,global
,nonlocal
- Asynchronous Programming Keywords: Keywords for asynchronous execution and managing coroutines.
- Keywords:
async
,await
__List of Python Keywords__
1. and: This is a logical operator which returns true if both the operands are true else returns false.
2. or: This is also a logical operator which returns true if anyone operand is true else returns false.
3. not: This is again a logical operator it returns True if the operand is false else returns false.
4. if: This is used to make a conditional statement.
5. elif: Elif is a condition statement used with an if statement. The elif statement is executed if the previous conditions were not true.
6. else: Else is used with if and elif conditional statements. The else block is executed if the given condition is not true.
7. for: This is used to create a loop.
8. while: This keyword is used to create a while loop.
9. break: This is used to terminate the loop.
10. as: This is used to create an alternative.
11. def: It helps us to define functions.
12. lambda: It is used to define the anonymous function.
13. pass: This is a null statement which means it will do nothing.
14. return: It will return a value and exit the function.
15. True: This is a boolean value.
16. False: This is also a boolean value.
17. try: It makes a try-except statement.
18. with: The with keyword is used to simplify exception handling.
19. assert: This function is used for debugging purposes. Usually used to check the correctness of code
20. class: It helps us to define a class.
21. continue It continues to the next iteration of a loop
22. del It deletes a reference to an object.
23. except Used with exceptions, what to do when an exception occurs
24. finally: Finally is used with exceptions, a block of code that will be executed no matter if there is an exception or not.
25. from: It is used to import specific parts of any module.
26. global: This declares a global variable.
27. import: This is used to import a module.
28. in: It’s used to check whether a value is present in a list, range, tuple, etc.
29. is This is used to check if the two variables are equal or not.
30. none This is a special constant used to denote a null value or avoid. It’s important to remember, 0, any empty container(e.g empty list) do not compute to None
31. nonlocal: It’s declared a non-local variable.
32. raise This raises an exception.
33. yield It ends a function and returns a generator.
34. async It is used to create asynchronous coroutine.
35. await It releases the flow of control back to the event loop.