Python Programming Table of content:
Python Keywords | All 39 Reserved & Soft Explained +Code Examples
Python's simplicity and readability have made it a favorite among both novice and experienced programmers. Central to its clear syntax are keywords, i.e., reserved words that serve as the building blocks of Python code. These reserved words, such as if, for, and class, are integral to writing clear and efficient code. Understanding Python keywords is not just about memorizing a list; it's about grasping how they control the flow, logic, and functionality of your programs.
In this article, we will discuss the 35 official Python keywords, their categories, uses, and more with examples, enabling you to write more readable, maintainable, and effective code.
What Are Keywords In Python?
Python has a set of reserved words known as keywords that are integral to its syntax and structure.
- These keywords cannot be used as identifiers (such as variable names, function names, or class names) because they have predefined meanings that are integral to the language's functionality.
- Attempting to use a keyword as an identifier will result in a syntax error.
Analogy: Think of Python keywords like traffic signs on a road. Just as traffic signs direct the flow of vehicles and inform drivers of rules and regulations, Python keywords guide the flow of a program and define its structure. Ignoring or misusing traffic signs can lead to accidents or confusion; similarly, misusing Python keywords can lead to errors or unintended behavior in your code.
Example: Consider the if keyword, which is used to implement conditional statements in Python. It allows the program to make decisions based on certain conditions.
age = 20
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
In this example:
- The keyword if marks the statement to check whether the condition (age >= 18) is true.
- If true, it executes the indented block under it, printing "You are eligible to vote."
- If false, it executes the code under else, printing "You are not eligible to vote."
Here, if and else are keywords that control the flow of the program based on the condition provided.
List Of Python Keywords
As of Python 3.10, there are 35 standard keywords and 4 soft keywords. Below is a table listing each keyword, its syntax, a brief description, and an example demonstrating its usage:
|
Keyword |
Description |
Example |
|
False |
Boolean value representing false |
is_active = False |
|
None |
Represents the absence of a value |
result = None |
|
True |
Boolean value representing true |
is_valid = True |
|
and |
Logical AND operator |
if x > 0 and x < 10: |
|
as |
Alias for modules or context managers |
import math as m |
|
assert |
Debugging aid that tests a condition |
assert x > 0 |
|
async |
Defines an asynchronous function |
async def fetch_data(): |
|
await |
Waits for the result of an async function |
data = await fetch_data() |
|
break |
Exits the current loop prematurely |
if condition: break |
|
class |
Defines a new class |
class MyClass: |
|
continue |
Skips the rest of the loop and continues |
if x < 0: continue |
|
def |
Defines a new function |
def my_function(): |
|
del |
Deletes an object |
del my_list[0] |
|
elif |
Else if condition in the control flow |
elif x == 0: |
|
else |
Defines an alternative block in the control flow |
else: |
|
except |
Catches exceptions in try-except blocks |
except ValueError: |
|
finally |
Executes code regardless of exceptions |
finally: |
|
for |
Starts a for loop |
for i in range(5): |
|
from |
Imports specific parts of a module |
from math import pi |
|
global |
Declares a global variable |
global count |
|
if |
Starts a conditional statement |
if x > 0: |
|
import |
Imports a module |
import os |
|
in |
Checks for membership |
if item in list: |
|
is |
Tests object identity |
if x is y: |
|
lambda |
Creates an anonymous function |
lambda x: x * 2 |
|
nonlocal |
Declares a non-local variable |
nonlocal count |
|
not |
Logical NOT operator |
if not done: |
|
or |
Logical OR operator |
if x < 0 or y < 0: |
|
pass |
Null operation; placeholder |
pass |
|
raise |
Raises an exception |
raise ValueError("Invalid input") |
|
return |
Exits a function and returns a value |
return result |
|
try |
Starts a try-except block |
try: |
|
while |
Starts a while loop |
while x > 0: |
|
with |
Context manager for resource management |
with open('file.txt') as f: |
|
yield |
Returns a generator |
yield x |
Soft Keywords (Introduced In Python 3.10)
|
Keyword |
Description |
Example |
|
match |
Starts a pattern matching block |
match value: |
|
case |
Defines a pattern to match in a match block |
case 1: |
|
_ |
Wildcard pattern in match-case statements |
case _: |
|
type |
Introduced in Python 3.12, used in type alias declarations. |
type Point = tuple[float, float] |
These soft keywords are reserved in specific contexts and can be used as identifiers elsewhere in the code.
Types/Categories Of Python Keywords
Python programming language’s 35 keywords can be grouped based on their functionalities, making it easier to comprehend their roles within the language. This categorization aids in understanding how these keywords contribute to Python's syntax and control structures.
Below is a table that categorizes Python keywords, outlining their purposes, typical usage contexts, and the specific keywords within each category.
|
Category |
Purpose |
Usage Context |
Keywords |
|
Control Flow |
Directs the execution flow of the program based on conditions or loops. |
Conditional statements and loops |
if, elif, else, for, while, break, continue, pass |
|
Function and Class Definitions |
Defines functions and classes, enabling modular and object-oriented programming. |
Function and class declarations |
def, class, lambda, return, yield |
|
Exception Handling |
Manages errors and exceptions that occur during program execution. |
Error detection and handling |
try, except, finally, raise, assert |
|
Variable Scope/Handling |
Control the scope and accessibility of variables within different contexts. |
Variable declaration and scope management |
global, nonlocal, del |
|
Logical Operators |
Performs logical operations, often used in conditional statements. |
Boolean logic and condition evaluations |
and, or, not |
|
Membership and Identity Operators |
Checks for membership or identity between variables and objects. |
Comparisons and condition checks |
in, is |
|
Import and Module Management |
Facilitates the inclusion of external modules and packages. |
Importing and aliasing modules |
import, from, as |
|
Asynchronous Programming |
Supports asynchronous programming for concurrent execution. |
Async functions and event loops |
async, await |
|
Context Management |
Manages resources with context managers to ensure proper acquisition and release. |
Resource management (e.g., files) |
with, as |
|
Boolean and Null Values |
Represents truth values and the absence of a value. |
Boolean logic and null checks |
True, False, None |
|
Pattern Matching |
Enables structural pattern matching introduced in Python 3.10. |
Matching complex data structures |
match, case, _ |
|
Type Alias Definitions |
Defines type aliases to improve code readability and maintainability. |
Type hinting and static type checking. |
type |
Understanding these categories provides a structured approach to learning Python keywords, allowing for more efficient coding and better comprehension of Python's syntax and capabilities. In the next section, we will look at each of these categories in detail and explore how the keywords work with the help of code examples.
Control Flow Keywords In Python
Control flow is the backbone of any programming language, dictating the order in which individual statements, instructions, or function calls are executed or evaluated. In Python, control flow is managed through conditional statements, loops, and control statements that alter the execution path based on specific conditions. This mechanism allows developers to write dynamic and responsive programs that can make decisions, repeat tasks, and handle different scenarios effectively.
Python's control flow constructs are designed to be intuitive and readable, adhering to the language's philosophy of simplicity and clarity. By mastering these keywords, you can control the logic of your programs with precision and write code that is both efficient and easy to understand. The table below provides a list of the control flow keywords, followed by a code example.
|
Keyword |
Description |
|
if |
Executes a block of code if a specified condition is true. |
|
elif |
Specifies a new condition to test if the previous condition is false. |
|
else |
Executes a block of code if all preceding conditions are false. |
|
for |
Iterates over a sequence (such as a list, tuple, or string). |
|
Repeats a block of code as long as a specified condition is true. |
|
|
break |
Exits the nearest enclosing loop prematurely. |
|
continue |
Skips the rest of the code inside the loop for the current iteration. |
|
pass |
A null operation; it does nothing and is used as a placeholder. |
Code Example:
Output:
Processing number: 1
Processing number: 2
Three encountered, skipping iteration.
Processing number: 4
Five encountered, breaking the loop.
Code Explanation:
- Here, we begin by defining a for loop, using for keyword. The loop iterates over numbers 1 through 5.
- Inside, we use if-elif-else statements to define different scenarios:
- When the number is 3, the continue statement skips the rest of the loop's body and proceeds to the next iteration.
- When the number is 5, the break statement exits the loop immediately.
- For other numbers, the program uses the print() function to display a message–” Processing message:” with the number (using f-strings).
- The else block associated with the loop would be implemented only if the loop wasn't terminated by a break statement.
This example demonstrates how control flow keywords can be used to manage the execution path of a program effectively.
Function & Class Definition Keywords
In Python, functions and classes are fundamental building blocks that promote code reusability and organization.
- Functions allow you to encapsulate a sequence of statements that perform a specific task. They can accept input parameters and return outputs, making them essential for modular programming.
- Classes enable object-oriented programming by allowing you to define custom data types with attributes (data) and methods (functions) that operate on the data. This approach helps in modeling real-world entities and behaviors.
Python provides specific keywords to define functions and classes, as well as to handle special scenarios like anonymous functions and generators.
|
Keyword |
Description |
|
def |
Defines a function or method. |
|
return |
Exits a function and optionally returns a value to the caller. |
|
class |
Defines a new class. |
|
lambda |
Creates an anonymous function (a function without a name). |
|
yield |
Pauses a generator function and returns a value; resumes from this point on next call. |
Code Example:
Output:
Sum: 8
Product: 8
History:
8
Code Explanation:
- A Calculator class is defined with methods to add numbers and retrieve history. Here, we use the class and def keywords to define the class and methods, respectively.
- The add method uses the return keyword to return the sum of two numbers and stores the result in the history.
- The generator_example method demonstrates the use of the yield keyword to create a generator that yields each item in the history.
- A lambda function named multiply is defined as multiplying two numbers.
- An instance of Calculator is created, and its methods are used to perform operations and display results.
This example illustrates how function and class definition keywords work together to create organized and reusable code structures in Python.
Exception Handling Keywords In Python
In Python, exceptions are events that disrupt the normal flow of a program's execution. They typically occur due to unforeseen errors, such as dividing by zero, accessing an invalid index in a list, or attempting to open a non-existent file. Python provides a robust exception-handling mechanism to manage these situations gracefully and prevent abrupt program termination.
The core of this mechanism revolves around the try and except blocks, which are implemented using the Python keywords mentioned in the table below:
|
Keyword |
Description |
|
try |
Defines a block of code to test for errors. |
|
except |
Defines a block of code to handle the error. |
|
else |
Defines a block of code to execute if no errors or exceptions were raised. |
|
finally |
Defines a block of code to execute regardless of the result of the try and except blocks. |
|
raise |
Triggers an exception manually. |
|
assert |
Tests if a condition is true; if not, raises an AssertionError. |
Understanding and effectively utilizing these keywords is essential for writing robust and error-resistant Python code.
Code Example:
Output:
Enter first number: 10
Enter second number: 0
Error: Cannot divide by zero. (division by zero)
Execution completed.
Code Explanation:
- We define a function to divide numbers and use the try, except, else, and finally keywords to create an error-handling mechanism.
- try block: Attempts to perform the division operation.
- except ZeroDivisionError: Catches the specific error when dividing by zero and prints an error message.
- else block: Executes if no exceptions are raised in the try block, printing the result.
- finally block: Executes regardless of whether an exception occurred, indicating the end of execution.
- Then, we also define another function to take input from a user and check if the numbers are numeric using assert and built-in Python functions.
- assert statement: Ensures that the user inputs are numeric; otherwise, raises an AssertionError.
- Finally, we call for input; the block raises an error and handles everything gracefully, as shown in the output.
By understanding and utilizing these exception-handling keywords, you can write Python programs that are more resilient and capable of handling unexpected situations gracefully.
Quick Knowledge Check!
QUIZZ SNIPPET IS HERE
Variable Scope/Handling Python Keywords
In Python, understanding variable scope is essential for writing clean and efficient code. Scope determines the accessibility and lifespan of a variable within different parts of a program. Python provides specific keywords to manage variable scope and handle variables effectively: global, nonlocal, and del.
|
Keyword |
Description |
|
global |
Declares that a variable inside a function refers to a globally defined variable. |
|
nonlocal |
Declares that a variable inside a nested function refers to a variable in the nearest enclosing scope that is not global. |
|
del |
Deletes variables, list items, or dictionary entries. |
Code Example:
Output:
Global count: 1
Inner message: Hi
Outer message: Hi
Value of x before deletion: 10
Code Explanation:
- global Keyword: In the increment function, the global keyword is used to indicate that the function intends to modify the global variable count. Without declaring count as global, assigning to it inside the function would create a new local variable, leaving the global count unchanged.
- nonlocal Keyword: In the outer function, message is a variable in the enclosing scope of the nested inner function. By declaring message as nonlocal inside inner, we allow the nested function to modify the message variable from the enclosing outer function. This demonstrates how nonlocal enables inner functions to modify variables from their enclosing scopes.
- del Keyword: The del statement is used to delete variables. In the example, after assigning 10 to x, we delete it using del x. Attempting to access x after deletion would result in a NameError since x no longer exists in the namespace.
By mastering these keywords, you can effectively manage variable scopes and lifecycles in Python, leading to more predictable and maintainable code.
Operator Keywords In Python (Logical & Membership)
In Python, certain keywords function as operators, enabling you to perform logical operations, test object identity, and check membership within collections. Unlike many programming languages that use symbols (e.g., &&, ||, !) for these operations, Python opts for English words, enhancing code readability and clarity.
These operator keywords are integral to constructing expressions that control the flow of logic in your programs. They allow you to combine conditions, invert boolean values, and assess relationships between objects and collections.
|
Keyword |
Description |
|
and |
Logical AND; returns True if both operands are True. |
|
or |
Logical OR; returns True if at least one operand is True. |
|
not |
Logical NOT; inverts the boolean value of the operand. |
|
in |
Membership test; returns True if a value exists within a sequence or collection. |
|
is |
Identity test; returns True if two references point to the same object. |
Code Example:
Output:
Both conditions are True.
At least one condition is True.
x and y are not equal.
20 is in the list z.
True
False
Code Explanation:
- Logical AND (and): Evaluates to True only if both conditions are True.
- Logical OR (or): Evaluates to True if at least one condition is True.
- Logical NOT (not): Inverts the result of the condition.
- Membership Test (in): Checks if a value exists within a collection.
- Identity Test (is): Determines if two references point to the same object in memory.
- Logical AND (and): The condition x > 5 and y > 15 checks if both x is greater than 5 and y is greater than 15. Since x is 10 and y is 20, both conditions are true, so the message "Both conditions are True." is printed.
- Logical OR (or): The condition x < 5 or y > 15 evaluates whether at least one of the conditions is true. Here, x is not less than 5, but y is greater than 15, so the overall condition is true, resulting in the message "At least one condition is True." being printed.
- Logical NOT (not): The statement not x == y inverts the result of x == y. Since x (10) is not equal to y (20), x == y is false; applying not makes it true, leading to the message "x and y are not equal." being printed.
- Membership Test (in): The condition 20 in z checks if the value 20 exists within the Python list z. Since z contains [10, 20, 30], the condition is true, and "20 is in the list z." is printed.
- Identity Test (is):
- a is b evaluates to true because both variables reference the same object.
- a is c evaluates to false because, despite having identical contents, a and c are different objects in memory.
By understanding and utilizing these operator keywords, you can write more expressive and readable Python code that effectively handles logical operations and object comparisons.
Quick Knowledge Check
QUIZZ SNIPPET IS HERE
Module & Import Management Keywords
In Python, modules are files containing Python code that define functions, classes, and variables. They promote code reusability and better organization. To utilize code from one module in another, Python provides specific keywords that facilitate the import process.
- The import keyword is used to bring in entire modules, making their contents accessible using dot notation. For instance, import math allows access to the math module's functions like math.sqrt().
- The from keyword enables importing specific attributes or functions from a module directly into the current namespace. For example, from math import sqrt allows direct use of sqrt() without the math. prefix.
- The as keyword allows aliasing modules or functions during import, which can simplify code and prevent naming conflicts. For instance, import numpy as np lets you use np as a shorthand for numpy.
These keywords are essential for managing dependencies and structuring Python programs effectively.
|
Keyword |
Description |
|
import |
Imports a module into the current namespace. |
|
from |
Imports specific attributes or functions from a module. |
|
as |
Assigns an alias to a module or function during import. |
Code Example:
Output:
Square root of 16 is: 4.0
Square root of 25 is: 5.0
Current date and time: 2025-04-14 02:10:28.123456
Code Explanation:
- import math: Brings in the entire math module, allowing access to its functions using the math. prefix.
- from math import sqrt: Imports only the sqrt function from the math module, enabling direct use without the module prefix.
- import datetime as dt: Imports the datetime module and assigns it the alias dt, simplifying references to its classes and functions.
By understanding and utilizing these module and import management keywords, you can write more organized and maintainable Python code, effectively managing dependencies and namespaces.
Asynchronous Programming Keywords In Python
Asynchronous programming in Python allows for concurrent execution of tasks, enabling programs to handle operations like I/O-bound tasks more efficiently. This is particularly useful when dealing with tasks that might take an unpredictable amount of time, such as network requests or file operations.
Python introduces two keywords to facilitate asynchronous programming:
|
Keyword |
Description |
|
async |
Declares an asynchronous function (coroutine) that can be paused and resumed. |
|
await |
Pauses the execution of the coroutine until the awaited task completes. |
Code Example:
Output:
Program started.
Start fetching data…
Data fetched successfully.
Result: {'data': 123}
Code Explanation:
- async def fetch_data(): Defines an asynchronous function that simulates data fetching.
- await asyncio.sleep(2): Pauses the coroutine for 2 seconds, simulating a delay (like a network request). During this pause, other tasks can run concurrently.
- async def main(): Defines the main coroutine that calls fetch_data() and awaits its result.
- asyncio.run(main()): Executes the main() coroutine, managing the event loop automatically.
By using async and await, Python allows for writing non-blocking code that can handle multiple operations concurrently, leading to more efficient and responsive programs.
Quick Knowledge Check
QUIZZ SNIPPET IS HERE
Context Management Keywords In Python
In Python, context management refers to the handling of resources such as files, network connections, or locks, ensuring they are acquired and released appropriately. This is particularly important for managing resources that require setup and teardown operations, like opening and closing files.
Python's with statement simplifies exception handling and resource management by encapsulating the setup and teardown actions within a context manager. This approach ensures that resources are properly managed, even if errors occur within the block.
|
Keyword |
Description |
|
with |
Used to wrap the execution of a block of code within methods defined by a context manager. |
|
as |
Binds the result of the context manager's __enter__() method to a variable, allowing access to the resource within the block. |
Code Example:
Output (example.txt):
Hello, world!
Code Explanation:
- File Handling with with and as: The with statement is used to open a file in write mode. The file is automatically closed when the block is exited, even if exceptions occur within the block. The as keyword binds the opened file object to the variable file, allowing you to interact with it directly.
- Lock Management with with and as: In multithreaded programming, the with statement is used to acquire a lock, ensuring that only one thread can execute the critical section at a time. The as keyword binds the acquired lock to the variable acquired_lock, though it's not used further in this example. The lock is automatically released when the block is exited using the pass statement.
By utilizing the with and as keywords, you can write cleaner and more reliable code for resource management, reducing the risk of errors and ensuring that resources are properly cleaned up after use.
Boolean & Null Values In Python
In Python, Boolean and null values are fundamental for logic and control flow. They represent truth values and the absence of a value, respectively. Understanding these values and using these Python keywords is crucial for making decisions and handling conditions in your programs.
|
Keyword |
Description |
|
True |
Represents the Boolean value true. |
|
False |
Represents the Boolean value false. |
|
None |
Represents the absence of a value or a null value. |
Code Example:
Output:
Value is True
No value provided
Value is False
Code Explanation:
In this example, the function check_value takes an input and uses an if-elif-else statement to evaluate it as follows:
- If value is None, it returns "No value provided".
- If value is truthy (not None and not False), it returns "Value is True".
- Otherwise, it returns "Value is False".
This demonstrates how True, False, and None are used in conditional statements to control the flow of the program.
Pattern Matching/Soft Python Keywords
Introduced in Python 3.10, pattern matching keywords allows for more readable and expressive code when dealing with complex data structures. It is particularly useful for matching and destructuring objects, lists, and other data types.
|
Keyword |
Description |
|
match |
Begins a pattern-matching block. |
|
case |
Defines a pattern to match against. |
|
_ |
A wildcard pattern that matches anything. |
Code Example:
Output:
Success: OK
Error: Not Found
Code Explanation:
In this example, the function handle_response uses pattern matching to handle different types of responses:
- The match keyword initiates the pattern matching block.
- Each case defines a pattern to match against the response.
- The _ wildcard pattern matches any case not explicitly handled.
This approach of using the soft Python keywords provides a clear and concise way to handle various data structures.
Type Alias Definitions Keyword In Python
Type aliases in Python allow you to define custom names for existing types, enhancing code readability and maintainability. They are particularly useful in complex type hinting scenarios.
|
Keyword |
Description |
|
type |
Introduced in Python 3.12 to define type aliases. |
Code Example:
Output:
[2.0, 4.0, 6.0]
Code Explanation:
In this example:
- The type keyword is used to define Vector as a list of floats and Matrix as a list of Vector.
- The function scale_vector takes a Vector and a scalar, returning a new Vector with each element scaled by the scalar.
This demonstrates how type aliases can simplify complex type annotations and improve code clarity.
Conclusion
Python's keywords form the foundation of its syntax and programming paradigms. From controlling flow and managing exceptions to handling asynchronous operations and defining type aliases, these reserved words are integral to writing clear and efficient Python code. By understanding and effectively utilizing these keywords, you can enhance your coding proficiency and develop more robust applications.
Frequently Asked Questions
Q1: How many keywords are there in Python?
As of Python 3.13, there are 35 reserved keywords. These are predefined words that have special meanings and cannot be used as identifiers (like variable names).
Q2: What are soft keywords in Python?
Soft keywords are identifiers that act as keywords only in specific contexts. For example, match, case, type, and _ are soft keywords introduced in Python 3.10 for structural pattern matching. Outside their specific contexts, they can be used as regular identifiers.
Q3: How can I get a list of all the keywords in Python?
You can use the built-in keyword module in Python:
import keyword
print(keyword.kwlist) # Lists all reserved keywords
print(keyword.softkwlist) # Lists all soft keywords (Python 3.10+)
As mentioned in the code comments, the different functions provided in the keyword module list the keyword reserves in Python.
Q4: Can I use Python keywords as variable names?
No, Python keywords are reserved and cannot be used as identifiers such as variable names, function names, or any other identifiers. Attempting to do so will result in a SyntaxError. However, soft keywords can be used as identifiers when not in their special context.
Q5: Why are some keywords 'soft' in Python?
Soft keywords allow the introduction of new language features without breaking existing code. By reserving words only in specific contexts, Python maintains backward compatibility and flexibility.
This compiles our discussion on Python keywords. Here are a few more topics you must explore:
- Python Strings | Create, Format, Reassign & More (+Examples)
- Hello, World! Program In Python | 7 Easy Methods (With Examples)
- Python IDLE | The Ultimate Beginner's Guide With Images & Codes!
- How To Print Without Newline In Python? (Mulitple Ways + Examples)
- Python Libraries | Standard, Third-Party & More (Lists + Examples)
- Python String Manipulation | Handbook With Techniques & Examples