Python Keywords
Master all 35 reserved words that control Python's behavior
🔑 Python Keywords
Keywords are reserved words in Python that have special meanings and cannot be used as variable names. They form the foundation of Python's syntax and control the flow of your programs.
# Keywords in action
if True: # if, True are keywords
for i in range(5): # for, in are keywords
print(i) # print is a function, not keyword
else: # else is a keyword
pass # pass is a keyword
Keyword Categories
Control Flow
Direct program execution
if, elif, else
for, while
break, continue
pass, return
Definition
Create functions and classes
def, class
lambda
global, nonlocal
Logical
Boolean operations
and, or, not
is, in
True, False, None
Exception
Handle errors gracefully
try, except, finally
raise, assert
with, as
🔀 Control Flow Keywords
Keywords that control how your program executes
🔹 Conditional Keywords
# if, elif, else - Make decisions
age = 18
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
# Nested conditions
weather = "sunny"
temperature = 75
if weather == "sunny":
if temperature > 70:
print("Perfect day!")
else:
print("Sunny but cold")
else:
print("Not sunny")
🔹 Loop Keywords
# for - Loop through sequences
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# while - Loop with condition
count = 0
while count < 3:
print(f"Count: {count}")
count += 1
# break - Exit loop early
for i in range(10):
if i == 5:
break
print(i) # Prints 0, 1, 2, 3, 4
# continue - Skip to next iteration
for i in range(5):
if i == 2:
continue
print(i) # Prints 0, 1, 3, 4
🔹 Flow Control Keywords
# pass - Do nothing (placeholder)
def future_function():
pass # Will implement later
if True:
pass # Empty block
# return - Exit function with value
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # 8
# Multiple returns
def check_number(n):
if n > 0:
return "positive"
elif n < 0:
return "negative"
else:
return "zero"
🏗️ Definition Keywords
Keywords for creating functions, classes, and scopes
🔹 Function Definition
# def - Define function
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message)
# lambda - Anonymous function
square = lambda x: x ** 2
print(square(5)) # 25
# Lambda with multiple arguments
add = lambda a, b: a + b
print(add(3, 4)) # 7
🔹 Class Definition
# class - Define class
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
my_dog = Dog("Buddy")
print(my_dog.bark()) # Buddy says woof!
🔹 Scope Keywords
# global - Access global variable
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter) # 1
# nonlocal - Access enclosing scope
def outer():
x = 10
def inner():
nonlocal x
x += 1
return x
return inner()
print(outer()) # 11
⚖️ Logical Keywords
Keywords for logical operations and comparisons
🔹 Boolean Operators
# and - Both conditions must be True
age = 25
has_license = True
can_drive = age >= 18 and has_license
print(can_drive) # True
# or - At least one condition must be True
is_weekend = False
is_holiday = True
can_sleep_in = is_weekend or is_holiday
print(can_sleep_in) # True
# not - Reverse boolean value
is_raining = False
is_sunny = not is_raining
print(is_sunny) # True
🔹 Identity and Membership
# is - Check if same object
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is b) # False (different objects)
print(a is c) # True (same object)
print(a == b) # True (same content)
# in - Check membership
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("orange" in fruits) # False
text = "Hello World"
print("World" in text) # True
🔹 Special Values
# True, False - Boolean values
is_active = True
is_deleted = False
if is_active and not is_deleted:
print("User is active")
# None - Represents absence of value
result = None
if result is None:
print("No result yet")
def maybe_return_value(condition):
if condition:
return "value"
return None # Explicit None return
🛡️ Exception Keywords
Keywords for handling errors and exceptions
🔹 Exception Handling
# try, except - Handle errors
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
# Multiple exceptions
try:
data = [1, 2, 3]
print(data[10])
except (IndexError, KeyError) as e:
print(f"Error accessing data: {e}")
# finally - Always executes
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
finally:
print("Cleanup complete")
🔹 Raising Exceptions
# raise - Throw exception
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
try:
result = divide(10, 0)
except ValueError as e:
print(f"Error: {e}")
# assert - Debug check
def calculate_age(birth_year):
current_year = 2024
age = current_year - birth_year
assert age >= 0, "Age cannot be negative"
return age
try:
age = calculate_age(2030) # Will raise AssertionError
except AssertionError as e:
print(f"Assertion failed: {e}")
🔹 Context Management
# with, as - Context manager
with open("data.txt", "w") as file:
file.write("Hello, World!")
# File automatically closed
# Multiple context managers
with open("input.txt", "r") as infile, \
open("output.txt", "w") as outfile:
content = infile.read()
outfile.write(content.upper())
# Custom context manager
class Timer:
def __enter__(self):
import time
self.start = time.time()
return self
def __exit__(self, *args):
import time
print(f"Time taken: {time.time() - self.start:.2f}s")
with Timer():
# Some time-consuming operation
sum(range(1000000))
📋 Complete Keywords List
All 35 Python keywords organized by category
🔀 Control Flow (11):
if
,
elif
,
else
,
for
,
while
,
break
,
continue
,
pass
,
return
,
yield
,
await
🏗️ Definition (4):
def
,
class
,
lambda
,
async
⚖️ Logical (8):
and
,
or
,
not
,
is
,
in
,
True
,
False
,
None
🛡️ Exception (6):
try
,
except
,
finally
,
raise
,
assert
,
with
🔧 Other (6):
import
,
from
,
as
,
global
,
nonlocal
,
del
# Check all keywords
import keyword
print("All Python keywords:")
print(keyword.kwlist)
print(f"Total keywords: {len(keyword.kwlist)}")
# Check if word is keyword
print(f"Is 'if' a keyword? {keyword.iskeyword('if')}")
print(f"Is 'print' a keyword? {keyword.iskeyword('print')}")
# Keywords cannot be used as variable names
# This would cause SyntaxError:
# if = 5 # Error!
# def = "hello" # Error!
# But these are fine:
if_statement = 5
def_keyword = "hello"
print(f"Valid variable: {if_statement}")