Python Keywords: A Comprehensive Guide
Python keywords are reserved words that have special meanings and purposes within the Python programming language. These words cannot be used as identifiers (variable names, function names, class names, etc.) because they are part of the language's syntax. Understanding these keywords is fundamental to mastering Python programming.
What Are Python Keywords?
Keywords in Python are predefined, reserved words that are used to define the syntax and structure of the Python language. They are case-sensitive and cannot be used for any other purpose than their intended function. Python has a total of 35 keywords as of Python 3.9+.
Complete List of Python Keywords
| Category | Keywords | |----------|----------| | Control Flow | if, elif, else, for, while, break, continue, pass | | Functions | def, return, lambda, yield | | Classes & Objects | class, self (not technically a keyword but reserved) | | Exception Handling | try, except, finally, raise, assert | | Boolean & Logic | True, False, None, and, or, not, is, in | | Import & Modules | import, from, as, global, nonlocal | | Async Programming | async, await | | Context Management | with | | Deletion | del |
Detailed Explanation of Each Keyword
Control Flow Keywords
#### if, elif, else
These keywords are used for conditional execution of code blocks.
`python
Basic if statement
age = 18 if age >= 18: print("You are an adult") elif age >= 13: print("You are a teenager") else: print("You are a child")Nested conditions
score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F" print(f"Your grade is: {grade}")`Notes:
- if starts a conditional statement
- elif (else if) allows multiple conditions
- else provides a default case when no conditions are met
- Indentation is crucial in Python for defining code blocks
#### for
The for keyword creates loops that iterate over sequences.
`python
Iterating over a list
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I like {fruit}")Using range() with for loop
for i in range(5): print(f"Number: {i}")Iterating over dictionary
student_grades = {"Alice": 90, "Bob": 85, "Charlie": 92} for name, grade in student_grades.items(): print(f"{name}: {grade}")List comprehension with for
squares = [x2 for x in range(10) if x % 2 == 0] print(squares) # [0, 4, 16, 36, 64]`#### while
The while keyword creates loops that continue as long as a condition is true.
`python
Basic while loop
count = 0 while count < 5: print(f"Count is: {count}") count += 1While loop with user input
user_input = "" while user_input.lower() != "quit": user_input = input("Enter 'quit' to exit: ") if user_input.lower() != "quit": print(f"You entered: {user_input}")Infinite loop with break
while True: number = int(input("Enter a number (0 to exit): ")) if number == 0: break print(f"Square of {number} is {number2}")`#### break and continue
These keywords control loop execution flow.
`python
break example - exits the loop completely
for i in range(10): if i == 5: break print(i) # Prints 0, 1, 2, 3, 4continue example - skips current iteration
for i in range(10): if i % 2 == 0: continue print(i) # Prints 1, 3, 5, 7, 9Using break and continue with while
numbers = [1, 2, 3, 0, 4, 5, -1, 6] i = 0 while i < len(numbers): if numbers[i] == -1: break if numbers[i] == 0: i += 1 continue print(f"Processing: {numbers[i]}") i += 1`#### pass
The pass keyword is a null operation - it does nothing when executed.
`python
Placeholder for future implementation
def future_function(): pass # TODO: Implement this function laterEmpty class definition
class EmptyClass: passConditional with placeholder
x = 10 if x > 5: pass # Do nothing for now else: print("x is not greater than 5")Loop with conditional pass
for i in range(10): if i % 2 == 0: pass # Even numbers - do nothing else: print(f"Odd number: {i}")`Function Keywords
#### def
The def keyword defines functions.
`python
Basic function definition
def greet(name): return f"Hello, {name}!"Function with default parameters
def calculate_area(length, width=1): return length * widthFunction with variable arguments
def sum_all(*args): return sum(args)Function with keyword arguments
def create_profile(kwargs): profile = {} for key, value in kwargs.items(): profile[key] = value return profileExample usage
print(greet("Alice")) # Hello, Alice! print(calculate_area(5)) # 5 (width defaults to 1) print(calculate_area(5, 3)) # 15 print(sum_all(1, 2, 3, 4, 5)) # 15 print(create_profile(name="Bob", age=25, city="New York"))`#### return
The return keyword exits a function and optionally returns a value.
`python
Function returning a single value
def square(x): return x * xFunction returning multiple values
def divide_and_remainder(a, b): quotient = a // b remainder = a % b return quotient, remainderFunction with conditional returns
def check_sign(number): if number > 0: return "positive" elif number < 0: return "negative" else: return "zero"Early return pattern
def validate_age(age): if age < 0: return "Invalid age" if age < 18: return "Minor" return "Adult"Example usage
result = square(4) # 16 q, r = divide_and_remainder(17, 5) # q=3, r=2 sign = check_sign(-5) # "negative" status = validate_age(25) # "Adult"`#### lambda
The lambda keyword creates anonymous functions (lambda functions).
`python
Basic lambda function
square = lambda x: x 2 print(square(5)) # 25Lambda with multiple parameters
add = lambda x, y: x + y print(add(3, 4)) # 7Using lambda with built-in functions
numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(lambda x: x2, numbers)) print(squared_numbers) # [1, 4, 9, 16, 25]Filtering with lambda
even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # [2, 4]Sorting with lambda
students = [("Alice", 85), ("Bob", 90), ("Charlie", 78)] students.sort(key=lambda student: student[1]) # Sort by grade print(students) # [('Charlie', 78), ('Alice', 85), ('Bob', 90)]Lambda in list comprehension alternative
squared_evens = [(lambda x: x2)(x) for x in range(10) if x % 2 == 0] print(squared_evens) # [0, 4, 16, 36, 64]`#### yield
The yield keyword is used to create generator functions.
`python
Basic generator function
def count_up_to(n): count = 1 while count <= n: yield count count += 1Using the generator
counter = count_up_to(5) for num in counter: print(num) # Prints 1, 2, 3, 4, 5Generator for Fibonacci sequence
def fibonacci(n): a, b = 0, 1 for _ in range(n): yield a a, b = b, a + bUsing Fibonacci generator
fib_sequence = list(fibonacci(10)) print(fib_sequence) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Generator expression
squares_gen = (x2 for x in range(10)) print(list(squares_gen)) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]Infinite generator
def infinite_sequence(): num = 0 while True: yield num num += 1Use with caution - this is infinite!
infinite_gen = infinite_sequence()
for i, num in enumerate(infinite_gen):
if i >= 10:
break
print(num)
`Class and Object Keywords
#### class
The class keyword defines classes for object-oriented programming.
`python
Basic class definition
class Person: def __init__(self, name, age): self.name = name self.age = age def introduce(self): return f"Hi, I'm {self.name} and I'm {self.age} years old"Class with class variables
class Car: wheels = 4 # Class variable def __init__(self, make, model, year): self.make = make # Instance variable self.model = model # Instance variable self.year = year # Instance variable def start_engine(self): return f"The {self.year} {self.make} {self.model} engine is starting" @classmethod def get_wheels(cls): return cls.wheels @staticmethod def is_vehicle(): return TrueInheritance
class ElectricCar(Car): def __init__(self, make, model, year, battery_capacity): super().__init__(make, model, year) self.battery_capacity = battery_capacity def charge_battery(self): return f"Charging {self.battery_capacity}kWh battery"Example usage
person = Person("Alice", 30) print(person.introduce())car = Car("Toyota", "Camry", 2022) print(car.start_engine()) print(Car.get_wheels()) # 4 print(Car.is_vehicle()) # True
electric_car = ElectricCar("Tesla", "Model 3", 2023, 75)
print(electric_car.start_engine())
print(electric_car.charge_battery())
`
Exception Handling Keywords
#### try, except, finally, raise
These keywords handle exceptions and errors.
`python
Basic exception handling
def divide_numbers(a, b): try: result = a / b print(f"Result: {result}") return result except ZeroDivisionError: print("Error: Cannot divide by zero") return None except TypeError: print("Error: Invalid input types") return None finally: print("Division operation completed")Multiple exception types
def process_data(data): try: # Convert to integer and process number = int(data) result = 100 / number return result except (ValueError, TypeError) as e: print(f"Input error: {e}") return None except ZeroDivisionError: print("Cannot divide by zero") return None except Exception as e: print(f"Unexpected error: {e}") return None finally: print("Data processing attempt completed")Raising custom exceptions
class CustomError(Exception): def __init__(self, message): self.message = message super().__init__(self.message)def validate_age(age): try: if not isinstance(age, int): raise TypeError("Age must be an integer") if age < 0: raise ValueError("Age cannot be negative") if age > 150: raise CustomError("Age seems unrealistic") return f"Valid age: {age}" except (TypeError, ValueError, CustomError) as e: return f"Validation error: {e}"
Example usage
divide_numbers(10, 2) # Result: 5.0, Division operation completed divide_numbers(10, 0) # Error: Cannot divide by zero, Division operation completedprint(process_data("5")) # 20.0, Data processing attempt completed print(process_data("0")) # Cannot divide by zero, Data processing attempt completed print(process_data("abc")) # Input error: invalid literal for int()
print(validate_age(25)) # Valid age: 25
print(validate_age(-5)) # Validation error: Age cannot be negative
print(validate_age(200)) # Validation error: Age seems unrealistic
`
#### assert
The assert keyword is used for debugging and testing.
`python
Basic assertions
def calculate_average(numbers): assert len(numbers) > 0, "List cannot be empty" assert all(isinstance(n, (int, float)) for n in numbers), "All elements must be numbers" return sum(numbers) / len(numbers)Assertions in testing
def test_calculate_average(): # Test normal case result = calculate_average([1, 2, 3, 4, 5]) assert result == 3.0, f"Expected 3.0, got {result}" # Test single element result = calculate_average([10]) assert result == 10.0, f"Expected 10.0, got {result}" print("All tests passed!")Assertions for data validation
def withdraw_money(balance, amount): assert balance >= 0, "Balance cannot be negative" assert amount > 0, "Withdrawal amount must be positive" assert amount <= balance, "Insufficient funds" return balance - amountExample usage
try: avg = calculate_average([1, 2, 3, 4, 5]) print(f"Average: {avg}") # Average: 3.0 test_calculate_average() # All tests passed! new_balance = withdraw_money(1000, 200) print(f"New balance: {new_balance}") # New balance: 800 # This will raise AssertionError # calculate_average([]) except AssertionError as e: print(f"Assertion failed: {e}")`Boolean and Logic Keywords
#### True, False, None
These are built-in constants representing boolean and null values.
`python
Boolean values
is_sunny = True is_raining = FalseUsing in conditions
if is_sunny: print("It's a beautiful day!")if not is_raining: print("No need for an umbrella")
None represents absence of value
def find_user(user_id): users = {1: "Alice", 2: "Bob", 3: "Charlie"} return users.get(user_id) # Returns None if not founduser = find_user(4) if user is None: print("User not found") else: print(f"Found user: {user}")
Boolean operations
def check_conditions(a, b, c): result = { "all_true": a and b and c, "any_true": a or b or c, "not_a": not a, "a_is_none": a is None, "a_equals_none": a == None # Not recommended, use 'is None' } return resultExample usage
conditions = check_conditions(True, False, None) print(conditions){'all_true': False, 'any_true': True, 'not_a': False, 'a_is_none': False, 'a_equals_none': False}
`#### and, or, not
Logical operators for combining boolean expressions.
`python
Logical AND
def can_vote(age, is_citizen): return age >= 18 and is_citizenLogical OR
def needs_id(age, buying_alcohol, entering_club): return age < 21 or buying_alcohol or entering_clubLogical NOT
def is_weekend(day): weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] return not (day in weekdays)Complex logical expressions
def approve_loan(credit_score, income, debt_ratio, employment_years): good_credit = credit_score >= 700 sufficient_income = income >= 50000 low_debt = debt_ratio < 0.4 stable_employment = employment_years >= 2 # Multiple conditions basic_approval = good_credit and sufficient_income risk_assessment = low_debt and stable_employment return basic_approval and risk_assessmentShort-circuit evaluation
def safe_divide(a, b): return b != 0 and (a / b) # Returns False if b is 0, otherwise returns division resultExample usage
print(can_vote(20, True)) # True print(can_vote(17, True)) # False print(needs_id(25, True, False)) # True print(is_weekend("Saturday")) # True print(approve_loan(750, 60000, 0.3, 3)) # True print(safe_divide(10, 2)) # 5.0 print(safe_divide(10, 0)) # False`#### is, in
Identity and membership operators.
`python
'is' operator - checks object identity
a = [1, 2, 3] b = [1, 2, 3] c = aprint(a == b) # True (same content) print(a is b) # False (different objects) print(a is c) # True (same object)
Common use with None
def process_data(data=None): if data is None: data = [] return data'in' operator - membership testing
fruits = ["apple", "banana", "cherry"] print("apple" in fruits) # True print("grape" in fruits) # FalseUsing 'in' with strings
text = "Hello, World!" print("World" in text) # True print("world" in text) # False (case sensitive)Using 'in' with dictionaries (checks keys)
student_grades = {"Alice": 90, "Bob": 85, "Charlie": 92} print("Alice" in student_grades) # True print(90 in student_grades) # False (90 is a value, not a key)Combining 'not' with 'in'
def validate_username(username): forbidden_chars = ["@", "#", "$", "%"] return not any(char in username for char in forbidden_chars)Using 'in' with ranges
def is_valid_grade(grade): return grade in range(0, 101) # 0 to 100 inclusiveExample usage
print(validate_username("john_doe")) # True print(validate_username("john@doe")) # False print(is_valid_grade(85)) # True print(is_valid_grade(105)) # False`Import and Module Keywords
#### import, from, as
These keywords are used for importing modules and managing namespaces.
`python
Basic import
import math import os import sysUsing imported modules
print(math.pi) # 3.141592653589793 print(math.sqrt(16)) # 4.0 print(os.getcwd()) # Current working directoryImport specific functions/classes
from math import sqrt, pi, sin, cos from datetime import datetime, date, timedeltaUsing imported functions directly
print(sqrt(25)) # 5.0 print(pi) # 3.141592653589793 print(sin(pi/2)) # 1.0Import with alias
import numpy as np import pandas as pd from collections import defaultdict as ddUsing aliases
array = np.array([1, 2, 3, 4, 5]) # If numpy is installed
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) # If pandas is installed
default_dict = dd(list)Import all (not recommended)
from math import * # Imports all functions from math module
Conditional imports
try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = Falsedef fetch_data(url): if HAS_REQUESTS: response = requests.get(url) return response.json() else: raise ImportError("requests library not available")
Local imports (inside functions)
def analyze_data(): from statistics import mean, median, mode data = [1, 2, 2, 3, 4, 5, 5, 5] return { 'mean': mean(data), 'median': median(data), 'mode': mode(data) }Example usage
current_time = datetime.now() tomorrow = current_time + timedelta(days=1) print(f"Current time: {current_time}") print(f"Tomorrow: {tomorrow}")stats = analyze_data()
print(f"Statistics: {stats}")
`
#### global, nonlocal
These keywords modify variable scope.
`python
Global keyword
global_counter = 0def increment_global(): global global_counter global_counter += 1 return global_counter
def reset_global(): global global_counter global_counter = 0
Nonlocal keyword
def outer_function(): outer_variable = 10 def inner_function(): nonlocal outer_variable outer_variable += 5 return outer_variable def another_inner(): nonlocal outer_variable outer_variable *= 2 return outer_variable return inner_function, another_innerComplex example with both global and nonlocal
app_config = {"debug": False, "version": "1.0"}def create_logger(): log_level = "INFO" def set_log_level(level): nonlocal log_level log_level = level def log_message(message): global app_config timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") if app_config["debug"]: print(f"[{timestamp}] [{log_level}] {message}") else: print(f"[{log_level}] {message}") def enable_debug(): global app_config app_config["debug"] = True return set_log_level, log_message, enable_debug
Example usage
print(f"Initial counter: {global_counter}") print(f"After increment: {increment_global()}") print(f"After another increment: {increment_global()}") reset_global() print(f"After reset: {global_counter}")inner1, inner2 = outer_function() print(f"After inner1: {inner1()}") # 15 print(f"After inner2: {inner2()}") # 30
set_level, log, enable_debug = create_logger()
log("Application started")
set_level("DEBUG")
log("Debug message")
enable_debug()
log("Debug message with timestamp")
`
Asynchronous Programming Keywords
#### async, await
These keywords are used for asynchronous programming.
`python
import asyncio
import aiohttp # This would need to be installed: pip install aiohttp
from datetime import datetime
Basic async function
async def greet_async(name, delay=1): print(f"Hello {name}, starting at {datetime.now()}") await asyncio.sleep(delay) # Non-blocking sleep print(f"Goodbye {name}, ending at {datetime.now()}") return f"Greeted {name}"Async function that calls other async functions
async def multiple_greetings(): # Sequential execution await greet_async("Alice", 1) await greet_async("Bob", 1) # Concurrent execution task1 = greet_async("Charlie", 2) task2 = greet_async("David", 2) results = await asyncio.gather(task1, task2) return resultsAsync context manager
class AsyncResource: async def __aenter__(self): print("Acquiring async resource") await asyncio.sleep(0.1) return self async def __aexit__(self, exc_type, exc_val, exc_tb): print("Releasing async resource") await asyncio.sleep(0.1) async def do_work(self): print("Doing async work") await asyncio.sleep(0.5) return "Work completed"Async generator
async def async_counter(n): for i in range(n): await asyncio.sleep(0.1) yield iReal-world example: async web requests (conceptual)
async def fetch_url(session, url): """Fetch a single URL asynchronously""" try: async with session.get(url) as response: return await response.text() except Exception as e: return f"Error fetching {url}: {e}"async def fetch_multiple_urls(urls): """Fetch multiple URLs concurrently""" async with aiohttp.ClientSession() as session: tasks = [fetch_url(session, url) for url in urls] results = await asyncio.gather(*tasks) return results
Running async functions
async def main(): print("=== Basic async example ===") result = await greet_async("World") print(f"Result: {result}") print("\n=== Multiple greetings ===") results = await multiple_greetings() print(f"Results: {results}") print("\n=== Async context manager ===") async with AsyncResource() as resource: result = await resource.do_work() print(f"Resource result: {result}") print("\n=== Async generator ===") async for number in async_counter(5): print(f"Generated: {number}") # Uncomment if aiohttp is available # print("\n=== Async web requests ===") # urls = ["http://httpbin.org/delay/1", "http://httpbin.org/delay/2"] # results = await fetch_multiple_urls(urls) # print(f"Fetched {len(results)} URLs")To run the async main function
if __name__ == "__main__": # asyncio.run(main()) # Uncomment to run print("Async examples defined (uncomment asyncio.run(main()) to execute)")`Context Management Keywords
#### with
The with keyword is used for context management, ensuring proper resource cleanup.
`python
File handling with context manager
def read_file_safely(filename): try: with open(filename, 'r') as file: content = file.read() return content except FileNotFoundError: return "File not found" except Exception as e: return f"Error reading file: {e}"Writing to file
def write_to_file(filename, content): with open(filename, 'w') as file: file.write(content) # File is automatically closed hereMultiple context managers
def copy_file(source, destination): with open(source, 'r') as src, open(destination, 'w') as dst: content = src.read() dst.write(content)Custom context manager using class
class DatabaseConnection: def __init__(self, connection_string): self.connection_string = connection_string self.connection = None def __enter__(self): print(f"Connecting to database: {self.connection_string}") # Simulate connection self.connection = f"Connected to {self.connection_string}" return self.connection def __exit__(self, exc_type, exc_val, exc_tb): print("Closing database connection") self.connection = None if exc_type: print(f"Exception occurred: {exc_val}") return False # Don't suppress exceptionsContext manager using contextlib
from contextlib import contextmanager import time@contextmanager def timer(): start_time = time.time() print("Timer started") try: yield start_time finally: end_time = time.time() print(f"Timer ended. Elapsed time: {end_time - start_time:.2f} seconds")
Suppressing exceptions with contextlib
from contextlib import suppressdef safe_operation(): with suppress(ValueError, TypeError): # These exceptions will be silently ignored result = int("not_a_number") return result return None
Example usage
print("=== File operations ===")Create a test file
write_to_file("test.txt", "Hello, World!\nThis is a test file.") content = read_file_safely("test.txt") print(f"File content:\n{content}")print("\n=== Database context manager ===") with DatabaseConnection("postgresql://localhost:5432/mydb") as conn: print(f"Using connection: {conn}") # Do database operations here
print("\n=== Timer context manager ===") with timer() as start: # Simulate some work time.sleep(1) print(f"Work started at: {start}")
print("\n=== Exception suppression ===") result = safe_operation() print(f"Safe operation result: {result}") # None, because ValueError was suppressed
Cleanup
import os try: os.remove("test.txt") except FileNotFoundError: pass`Deletion Keyword
#### del
The del keyword deletes objects and variables.
`python
Deleting variables
x = 10 y = 20 print(f"x = {x}, y = {y}") del xprint(x) # This would raise NameError: name 'x' is not defined
Deleting list elements
numbers = [1, 2, 3, 4, 5] print(f"Original list: {numbers}") del numbers[2] # Remove element at index 2 print(f"After deleting index 2: {numbers}")Deleting slices
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] del numbers[2:5] # Remove elements from index 2 to 4 print(f"After deleting slice [2:5]: {numbers}")Deleting dictionary items
student_grades = {"Alice": 90, "Bob": 85, "Charlie": 92, "David": 88} print(f"Original grades: {student_grades}") del student_grades["Bob"] print(f"After deleting Bob: {student_grades}")Deleting object attributes
class Person: def __init__(self, name, age): self.name = name self.age = age self.email = Noneperson = Person("Alice", 30) person.email = "alice@example.com" print(f"Person attributes: name={person.name}, age={person.age}, email={person.email}")
del person.email
print(person.email) # This would raise AttributeError
Custom deletion behavior
class ManagedResource: def __init__(self, name): self.name = name self.resources = [] print(f"Created resource: {name}") def __del__(self): print(f"Cleaning up resource: {self.name}") self.resources.clear()Example usage
resource1 = ManagedResource("Database Connection") resource2 = ManagedResource("File Handle")Delete resources
del resource1 # Triggers __del__ methodresource2 will be deleted when it goes out of scope
Deleting in loops (be careful!)
data = {"a": 1, "b": 2, "c": 3, "d": 4}Wrong way - modifying dict while iterating
for key in data:
if data[key] % 2 == 0:
del data[key] # This can cause RuntimeError
Correct way - collect keys first
to_delete = [key for key, value in data.items() if value % 2 == 0] for key in to_delete: del data[key] print(f"After deleting even values: {data}")`Keyword Usage Best Practices
Performance Considerations
| Keyword | Performance Notes |
|---------|------------------|
| for | Generally faster than while for iteration |
| in | O(n) for lists, O(1) average for sets/dicts |
| is | Faster than == for identity comparison |
| lambda | Slightly slower than regular functions |
| yield | Memory efficient for large datasets |
Common Mistakes and How to Avoid Them
`python
Mistake 1: Using '==' instead of 'is' for None
def bad_none_check(value): return value == None # Don't do thisdef good_none_check(value): return value is None # Do this instead
Mistake 2: Modifying list while iterating
def remove_even_numbers_bad(numbers): for i, num in enumerate(numbers): if num % 2 == 0: del numbers[i] # Can cause IndexError return numbersdef remove_even_numbers_good(numbers): return [num for num in numbers if num % 2 != 0]
Mistake 3: Not using context managers for resources
def read_file_bad(filename): file = open(filename, 'r') content = file.read() # File might not be closed if exception occurs file.close() return contentdef read_file_good(filename): with open(filename, 'r') as file: return file.read() # File automatically closed
Mistake 4: Overusing lambda for complex operations
def complex_operation_bad(): # Too complex for lambda process = lambda x: x 2 if x > 0 else abs(x) 3 if x < -10 else 0 return processdef complex_operation_good():
def process(x):
if x > 0:
return x * 2
elif x < -10:
return abs(x) * 3
else:
return 0
return process
`
Advanced Keyword Combinations
Combining Multiple Keywords
`python
Complex control flow
def process_user_input(): while True: try: user_input = input("Enter a number (or 'quit' to exit): ") if user_input.lower() == 'quit': break number = float(user_input) if number < 0: continue elif number == 0: pass # Do nothing for zero else: result = 1 / number print(f"1/{number} = {result}") except ValueError: print("Please enter a valid number") except KeyboardInterrupt: print("\nProgram interrupted by user") break except Exception as e: print(f"Unexpected error: {e}") finally: print("Processing completed for this input")Combining async with context management
async def async_file_processor(): async def async_file_reader(filename): # Simulated async file reading await asyncio.sleep(0.1) with open(filename, 'r') as f: return f.read() try: with timer(): # Custom context manager from earlier content = await async_file_reader('test.txt') return content except FileNotFoundError: return "File not found"Complex class with multiple keywords
class AsyncDataProcessor: def __init__(self, name): self.name = name self._data = [] async def __aenter__(self): print(f"Starting async processor: {self.name}") return self async def __aexit__(self, exc_type, exc_val, exc_tb): print(f"Shutting down processor: {self.name}") if exc_type: print(f"Exception during processing: {exc_val}") return False def __del__(self): print(f"Processor {self.name} garbage collected") async def process_data(self, data): for item in data: try: if item is None: continue elif isinstance(item, str) and item.lower() == 'stop': break else: processed = await self._async_transform(item) self._data.append(processed) yield processed except Exception as e: raise ValueError(f"Error processing {item}: {e}") async def _async_transform(self, item): await asyncio.sleep(0.01) # Simulate async work return item * 2 if isinstance(item, (int, float)) else str(item).upper()`Summary
Python keywords are fundamental building blocks that define the language's syntax and capabilities. Understanding these keywords and their proper usage is essential for writing effective Python code. Key takeaways include:
1. Control Flow Keywords (if, for, while, break, continue, pass) manage program execution flow
2. Function Keywords (def, return, lambda, yield) define and control functions and generators
3. Exception Handling Keywords (try, except, finally, raise, assert) manage errors gracefully
4. Boolean and Logic Keywords (True, False, None, and, or, not, is, in) handle logical operations
5. Import Keywords (import, from, as, global, nonlocal) manage modules and scope
6. Async Keywords (async, await) enable asynchronous programming
7. Context Management (with) ensures proper resource handling
8. Object Management (class, del) handle object creation and cleanup
Mastering these keywords and understanding their interactions will significantly improve your Python programming skills and enable you to write more robust, efficient, and maintainable code.