Python comes with a rich set of predefined keywords that form the backbone of its syntax. These aren't functions you define — they’re built into the language and serve specific roles in control flow, error handling, logic, and structure. Here’s a walk-through of the most essential ones, with explanations and syntax examples to help you master them.
Python’s exception handling is clean and readable, thanks to keywords like try, except, finally, raise, and assert.
try: Begins a block of code that might raise an exception.try: risky_operation()
except: Catches and handles exceptions raised in thetryblock.except ValueError: print("Invalid value")
finally: Runs regardless of whether an exception occurred — perfect for cleanup.finally: close_resources()
raise: Manually triggers an exception.raise RuntimeError("Something went wrong")
assert: Validates a condition and raisesAssertionErrorif it fails.assert x > 0, "x must be positive"
Python’s loop constructs are intuitive and flexible, allowing you to iterate, skip, or exit based on conditions.
for: Iterates over items in a sequence.for item in items: print(item)
while: Loops as long as a condition is true.while not done: process()
break: Exits the loop immediately.if error_detected: break
continue: Skips the current iteration and moves to the next.if not valid: continue
pass: A no-op placeholder — useful when the syntax requires a block but you don’t want to do anything yet.if condition_met: pass
Python’s conditional keywords let you branch your logic cleanly.
if: Executes a block if the condition is true.if score >= 90: print("Excellent")
elif: Adds additional conditions.elif score >= 75: print("Good")
else: Executes if no prior conditions matched.else: print("Needs improvement")
Defining reusable blocks of logic or object-oriented structures is straightforward with these keywords.
def: Declares a function.def greet(name): return f"Hello, {name}"
class: Declares a class.class User: def __init__(self, name): self.name = name
return: Sends a value back from a function.return result
yield: Used in generators to return a value and pause execution.yield item
Python’s modularity is powered by its import system.
import: Brings in a module.import os
from: Imports specific parts of a module.from math import sqrt
as: Assigns an alias to a module or function.import numpy as np
These keywords support context management, scope control, and logical operations.
with: Manages resources like files or locks using context managers.with open("data.txt") as file: content = file.read()
lambda: Creates anonymous functions.square = lambda x: x * x
global: Declares a variable as global inside a function.global counter
nonlocal: Refers to variables in the nearest enclosing scope (not global).nonlocal total
del: Deletes a variable or item.del my_list[0]
is: Checks identity (not equality).if a is b: print("Same object")
in: Checks membership.if "admin" in roles: grant_access()
not,and,or: Logical operators.if not error and ready or override: proceed()