Python Programming Keywords Guide
35 Keywords Reserved Words

Python Keywords Complete Guide

Learn all 35 Python keywords with detailed examples and usage. Keywords are reserved words that have special meaning in Python programming language.

35 Keywords

Complete list

8 Categories

By usage

Reserved

Cannot use as variables

Examples

Practical usage

What are Python Keywords?

Keywords are reserved words in Python that have special meaning and cannot be used as variable names, function names, or any other identifiers. They are the building blocks of Python programming language syntax.

Key Facts

  • Python has 35 keywords (as of Python 3.12)
  • Keywords are case-sensitive (all lowercase except True, False, None)
  • They cannot be used as identifiers (variable names, function names, etc.)
  • Keywords define the syntax and structure of Python programs
  • They are reserved for special purposes only

Quick View: All Python Keywords

False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield

Hover over keywords to see effect. Colors indicate categories.

Check Python Keywords Programmatically
# How to check Python keywords programmatically
import keyword

# Get list of all keywords
print("All Python Keywords:")
print(keyword.kwlist)

# Check if a word is a keyword
print("\nChecking specific words:")
print(f"'if' is keyword: {keyword.iskeyword('if')}")
print(f"'print' is keyword: {keyword.iskeyword('print')}")
print(f"'for' is keyword: {keyword.iskeyword('for')}")
print(f"'hello' is keyword: {keyword.iskeyword('hello')}")

# Number of keywords
print(f"\nTotal keywords in Python: {len(keyword.kwlist)}")

# Categories count (approximate)
categories = {
    'Control Flow': ['if', 'elif', 'else', 'for', 'while', 'break', 'continue', 'pass'],
    'Functions': ['def', 'return', 'lambda', 'yield'],
    'Classes': ['class'],
    'Modules': ['import', 'from', 'as'],
    'Exception': ['try', 'except', 'finally', 'raise', 'assert'],
    'Logic': ['and', 'or', 'not', 'is', 'in', 'not'],
    'Scope': ['global', 'nonlocal'],
    'Values': ['True', 'False', 'None'],
    'Async': ['async', 'await'],
    'Other': ['del', 'with']
}

print("\nKeywords by category:")
for category, keywords in categories.items():
    print(f"{category}: {len(keywords)} keywords")
Important: You cannot use keywords as variable names. This will cause a syntax error.
if = 10 # SyntaxError: invalid syntax

Complete Python Keywords Reference

This table contains all 35 Python keywords with their descriptions, categories, and importance.

Keyword Category Description Importance Example
if Control Flow Conditional statement - executes block if condition is True ⭐⭐⭐⭐⭐
Essential for decision making
if x > 10:
elif Control Flow Else if - checks another condition if previous if/elif is False ⭐⭐⭐⭐⭐
Multiple condition handling
elif x == 10:
else Control Flow Executes block when all if/elif conditions are False ⭐⭐⭐⭐⭐
Default case handler
else:
for Loop Iterates over sequence (list, tuple, string, range, etc.) ⭐⭐⭐⭐⭐
Essential for iteration
for i in range(5):
while Loop Repeats block while condition is True ⭐⭐⭐⭐⭐
Condition-based looping
while x < 10:
break Loop Exits the current loop immediately ⭐⭐⭐⭐
Loop control
break
continue Loop Skips current iteration and continues with next ⭐⭐⭐⭐
Loop control
continue
def Function Defines a function ⭐⭐⭐⭐⭐
Function definition
def my_func():
return Function Exits function and returns value to caller ⭐⭐⭐⭐⭐
Function output
return result
lambda Function Creates anonymous (inline) functions ⭐⭐⭐⭐
Functional programming
lambda x: x*2
class Class Defines a class (blueprint for objects) ⭐⭐⭐⭐⭐
OOP fundamental
class MyClass:
import Module Imports modules/packages for use in current program ⭐⭐⭐⭐⭐
Code reuse
import math
from Module Imports specific attributes/functions from module ⭐⭐⭐⭐⭐
Selective import
from math import sqrt
as Module Creates alias for imported module/function ⭐⭐⭐⭐
Avoid naming conflicts
import numpy as np
try Exception Tests block of code for errors ⭐⭐⭐⭐⭐
Error handling
try:
except Exception Handles specific exceptions ⭐⭐⭐⭐⭐
Error handling
except ValueError:
finally Exception Executes code regardless of try-except result ⭐⭐⭐⭐
Cleanup operations
finally:
raise Exception Raises (throws) an exception ⭐⭐⭐⭐
Custom errors
raise ValueError()
assert Exception Tests if condition is True, raises AssertionError if False ⭐⭐⭐
Debugging
assert x > 0
and Logic Logical AND operator - True if both conditions are True ⭐⭐⭐⭐⭐
Boolean logic
x > 0 and x < 10
or Logic Logical OR operator - True if at least one condition is True ⭐⭐⭐⭐⭐
Boolean logic
x < 0 or x > 100
not Logic Logical NOT operator - reverses boolean value ⭐⭐⭐⭐⭐
Boolean logic
not x == 10
in Logic Membership operator - checks if value exists in sequence ⭐⭐⭐⭐⭐
Collection operations
x in [1, 2, 3]
is Logic Identity operator - checks if two objects are same ⭐⭐⭐⭐
Object comparison
x is None
True Value Boolean true value (note: capital T) ⭐⭐⭐⭐⭐
Boolean logic
is_valid = True
False Value Boolean false value (note: capital F) ⭐⭐⭐⭐⭐
Boolean logic
is_done = False
None Value Represents absence of value (similar to null) ⭐⭐⭐⭐⭐
Null representation
result = None
global Scope Declares variable as global (accessible everywhere) ⭐⭐⭐
Variable scope
global counter
nonlocal Scope Declares variable as nonlocal (in nested functions) ⭐⭐⭐
Variable scope
nonlocal x
del Other Deletes object/variable from memory ⭐⭐⭐
Memory management
del my_list[0]
pass Other Null operation - placeholder for future code ⭐⭐⭐⭐
Code structure
pass
with Other Context manager - handles resource management ⭐⭐⭐⭐
Resource handling
with open('file.txt') as f:
yield Other Returns generator value (used in generator functions) ⭐⭐⭐⭐
Memory efficiency
yield item
async Async Declares asynchronous function/coroutine ⭐⭐⭐
Async programming
async def fetch():
await Async Waits for asynchronous operation to complete ⭐⭐⭐
Async programming
await response
Importance Rating Guide:
  • ⭐⭐⭐⭐⭐ - Essential: Must know for every Python programmer
  • ⭐⭐⭐⭐ - Important: Used frequently in most programs
  • ⭐⭐⭐ - Useful: Important for specific use cases
  • ⭐⭐ - Specialized: Used in specific scenarios
  • ⭐ - Rare: Seldom used in general programming

Detailed Keyword Examples

Let's explore some important keywords with detailed examples and explanations.

if
Control Flow: if, elif, else

Decision making in Python

Conditional Statements Example
# if, elif, else - Complete example
score = 85

if score >= 90:
    grade = "A"
    print("Excellent!")
elif score >= 80:
    grade = "B"
    print("Good job!")
elif score >= 70:
    grade = "C"
    print("You passed!")
elif score >= 60:
    grade = "D"
    print("You passed, but need improvement.")
else:
    grade = "F"
    print("Sorry, you failed.")

print(f"Score: {score}, Grade: {grade}")

# Nested if statements
age = 25
has_license = True

if age >= 18:
    if has_license:
        print("You can drive!")
    else:
        print("You need a license to drive.")
else:
    print("You're too young to drive.")
for
Loop Keywords: for, while, break, continue

Iteration and loop control

Loop Control Examples
# for loop with break and continue
print("=== for loop examples ===")
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using break to exit loop early
for num in numbers:
    if num == 5:
        print("Found 5, breaking loop!")
        break
    print(num)

print("\n=== Using continue ===")
# Using continue to skip specific items
for num in numbers:
    if num % 2 == 0:  # Skip even numbers
        continue
    print(f"Odd number: {num}")

print("\n=== while loop example ===")
# while loop with condition
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1

# Infinite loop with break
print("\n=== Infinite loop with break ===")
while True:
    user_input = input("Enter 'quit' to exit: ")
    if user_input.lower() == 'quit':
        print("Goodbye!")
        break
    print(f"You entered: {user_input}")
def
Function & Class Keywords: def, class, return

Creating functions and classes

Functions and Classes Examples
# Function definition with def and return
def calculate_area(radius):
    """Calculate area of circle"""
    pi = 3.14159
    area = pi * radius ** 2
    return area

# Lambda function (anonymous function)
square = lambda x: x ** 2

# Class definition
class Rectangle:
    """Rectangle class with area calculation"""
    
    def __init__(self, width, height):
        # Constructor method
        self.width = width
        self.height = height
    
    def area(self):
        """Calculate area of rectangle"""
        return self.width * self.height
    
    def perimeter(self):
        """Calculate perimeter"""
        return 2 * (self.width + self.height)

# Using the function and class
circle_area = calculate_area(5)
print(f"Area of circle with radius 5: {circle_area:.2f}")

print(f"Square of 4 using lambda: {square(4)}")

# Create rectangle object
rect = Rectangle(10, 5)
print(f"Rectangle area: {rect.area()}")
print(f"Rectangle perimeter: {rect.perimeter()}")
try
Exception Keywords: try, except, finally, raise

Error handling in Python

Exception Handling Examples
# Basic try-except
try:
    number = int(input("Enter a number: "))
    result = 100 / number
    print(f"100 divided by {number} is {result}")
except ValueError:
    print("Error: That's not a valid number!")
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    print("This always executes, with or without errors.")

# Using raise to create custom exceptions
def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    elif age > 150:
        raise ValueError("Age seems unrealistic!")
    return True

# Using assert for debugging
def calculate_discount(price, discount_rate):
    assert 0 <= discount_rate <= 1, "Discount rate must be between 0 and 1"
    return price * (1 - discount_rate)

# Test the functions
try:
    validate_age(-5)
except ValueError as e:
    print(f"Validation error: {e}")

print(f"Discount price: {calculate_discount(100, 0.2)}")

Common Mistakes & Best Practices

Common Mistakes
  • Using keywords as variable names: class = "Python"
  • Incorrect case: true instead of True
  • Missing colons: if x > 10 (should be if x > 10:)
  • Using 'is' for value comparison: x is 10 (use == instead)
  • Forgetting 'self' in class methods
  • Missing 'return' in functions that need to return value
Best Practices
  • Use descriptive variable names (not keywords)
  • Always use correct case for True, False, None
  • Use 'is' for identity checks (None, True, False)
  • Use '==' for value comparisons
  • Include 'else' clause for completeness
  • Use 'with' for file operations (auto-closes files)
  • Handle exceptions specifically (not bare except)
Good vs Bad Practices
# BAD PRACTICES - AVOID THESE
# Using keyword as variable name (ERROR)
# class = "Python"  # SyntaxError

# Wrong case for boolean
# is_valid = true  # NameError: true is not defined

# Using 'is' for value comparison
x = 10
# if x is 10:  # Avoid - use == for values
#     print("x is 10")

# Bare except (catches everything)
try:
    result = 10 / 0
except:  # Too broad!
    print("An error occurred")

# GOOD PRACTICES - FOLLOW THESE
# Use descriptive names
class_name = "Python Programming"

# Correct case for boolean
is_valid = True

# Use 'is' only for identity checks
if x is None:
    print("x is None")

# Use '==' for value comparison
if x == 10:
    print("x equals 10")

# Specific exception handling
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Cannot divide by zero: {e}")
except Exception as e:
    print(f"Other error: {e}")

# Use 'with' for file handling (auto-closes)
with open('data.txt', 'r') as file:
    content = file.read()
# File automatically closed here

Keyword Categories Summary

Control Flow (8)
  • if, elif, else
  • and, or, not
  • in, is
  • lambda, assert

Purpose: Decision making and flow control

Loops (9)
  • for, while
  • break, continue
  • pass, yield
  • async, await
  • finally

Purpose: Iteration and loop control

Functions (4)
  • def
  • return
  • lambda
  • yield

Purpose: Function definition and control

Classes (1)
  • class

Purpose: Object-oriented programming

Modules (3)
  • import
  • from
  • as

Purpose: Code organization and reuse

Exceptions (5)
  • try, except
  • finally
  • raise
  • assert

Purpose: Error handling and debugging

Values (3)
  • True
  • False
  • None

Purpose: Special constant values

Scope (2)
  • global
  • nonlocal

Purpose: Variable scope management

Other (2)
  • del
  • with

Purpose: Miscellaneous operations

Keywords Knowledge Check

Test your understanding of Python keywords with this interactive section.

Identify the Keywords
# Which words in this code are Python keywords?
import math
from datetime import date

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def is_adult(self):
        return self.age >= 18

def calculate_stats(numbers):
    if not numbers:
        return None
    
    total = 0
    for num in numbers:
        total += num
    
    average = total / len(numbers)
    return average

# Answer: import, from, class, def, __init__, self, return, if, not, None, for, in, len

# Keywords used: import, from, class, def, return, if, not, None, for, in
# Not keywords: math, datetime, date, Student, __init__, self, is_adult, calculate_stats, 
#               numbers, total, num, average, len
Quick Tips:
  • Use import keyword; print(keyword.kwlist) to see all keywords
  • Use keyword.iskeyword('word') to check if a word is a keyword
  • Most keywords are lowercase except True, False, None
  • If you get SyntaxError when using a word as variable, it's probably a keyword

Key Takeaways

  • Python has 35 keywords (reserved words with special meaning)
  • Keywords are case-sensitive - True, False, None have capital first letter
  • You cannot use keywords as variable names, function names, or any identifiers
  • Keywords are categorized by function: Control Flow, Loops, Functions, Classes, Modules, etc.
  • Most important keywords: if, else, for, while, def, class, import, try, except
  • Use import keyword module to work with keywords programmatically
  • Understanding keywords is essential for writing correct Python syntax
  • Always use proper indentation with keywords (Python uses indentation instead of braces)
Next Topics: Learn about Python Input & Output - how to get user input and display output in Python programs