In Python, keywords are reserved words that have special meanings. These words are part of the language syntax and cannot be used as identifiers (variable names, function names, etc.). Keywords help define the structure and functionality of Python programs.
we’ll cover:
- What keywords are.
- A list of Python keywords.
- Examples of how to use them effectively.
What are Python Keywords?
Keywords in Python:
- Are predefined and reserved by the language.
- Cannot be used for anything other than their intended purpose.
- Are case-sensitive (e.g.,
if
is a keyword, butIf
is not).
List of Python Keywords
As of Python 3.10, here is the complete list of keywords:
Keywords | Description |
---|---|
False , True |
Boolean values, representing truth and falsehood. |
None |
Represents the absence of a value. |
and , or , not |
Logical operators for combining Boolean expressions. |
if , elif , else |
Conditional statements. |
for , while , break , continue |
Loop control keywords. |
in , is |
Membership and identity operators. |
def , return , yield |
Define functions and return values. |
class , del , pass |
Define classes, delete objects, or skip code. |
try , except , finally , raise |
Handle exceptions and errors. |
import , from , as |
Import modules or rename them. |
with , async , await |
Context managers and asynchronous programming. |
global , nonlocal |
Modify the scope of variables. |
lambda |
Create anonymous (inline) functions. |
assert |
Debugging tool to test conditions. |
To view keywords in your Python environment, use the keyword
module:
import keyword print(keyword.kwlist) # Prints all Python keywords
Using Python Keywords: Examples
Let’s explore some of these keywords with examples.
1. Conditional Statements
Keywords: if
, elif
, else
Conditional statements are used to execute code based on conditions.
age = 18 if age < 18: print("You are a minor.") elif age == 18: print("You just became an adult!") else: print("You are an adult.")
2. Loops
Keywords: for
, while
, break
, continue
Loops allow you to repeat actions. Use break
to exit a loop early and continue
to skip the rest of the current iteration.
Example:
# Using for loop for i in range(5): if i == 3: break # Exit the loop when i is 3 print(i) # Using while loop x = 0 while x < 5: x += 1 if x == 3: continue # Skip the rest of the iteration when x is 3 print(x)
3. Boolean Values and Logical Operators
Keywords: True
, False
, and
, or
, not
These keywords are used in logical expressions.
Example:
is_raining = False is_weekend = True if not is_raining and is_weekend: print("Perfect day for a picnic!") else: print("Stay indoors.")
4. Defining Functions
Keywords: def
, return
Functions are reusable blocks of code. Use return
to send a result back to the caller.
Example:
def greet(name): return f"Hello, {name}!" print(greet("Alice")) # Output: Hello, Alice!
5. Exception Handling
Keywords: try
, except
, finally
, raise
Handle runtime errors using exception handling keywords.
Example:
try: num = int(input("Enter a number: ")) print(f"The number you entered is {num}") except ValueError: print("That's not a valid number!") finally: print("Program execution completed.")
6. Classes
Keywords: class
, pass
Create custom objects with classes. Use pass
as a placeholder when no code is needed.
Example:
class Person: pass # Placeholder for future code person = Person() print(type(person)) # Output: <class '__main__.Person'>
7. Global and Local Scopes
Keywords: global
, nonlocal
Control variable scope with global
and nonlocal
.
Example:
# Using global x = 10 def update_global(): global x x = 20 update_global() print(x) # Output: 20 # Using nonlocal def outer(): y = 5 def inner(): nonlocal y y = 10 inner() print(y) outer() # Output: 10
8. Lambda Functions
Keyword: lambda
Create small, anonymous functions using lambda
.
Example:
square = lambda x: x ** 2 print(square(4)) # Output: 16
9. Context Management
Keyword: with
Use with
for handling resources like file operations.
Example:
with open("example.txt", "w") as file: file.write("Hello, World!") # Automatically closes the file
10. Importing Modules
Keywords: import
, from
, as
Import modules and rename them if needed.
Example:
import math as m print(m.sqrt(16)) # Output: 4.0