Reserved Words

Python reserved words (keywords) are special words that have predefined meanings and cannot be used as variable names, function names, or any other identifiers. This reference provides a complete list of all Python keywords with their purposes and usage examples.

Python Keywords Reference

KeywordPurposeCategoryUsage ExampleDescription
andLogical operatorOperatorif x > 0 and y > 0:Logical AND operation
asAlias creationStatementimport numpy as npCreate alias for imports or with statements
assertDebugging aidStatementassert x > 0, "x must be positive"Test conditions during development
breakLoop controlControl FlowbreakExit current loop immediately
classClass definitionDefinitionclass MyClass:Define a new class
continueLoop controlControl FlowcontinueSkip to next iteration of loop
defFunction definitionDefinitiondef my_function():Define a new function
delObject deletionStatementdel my_variableDelete objects or variables
elifConditionalControl Flowelif condition:Additional condition in if statement
elseConditional/LoopControl Flowelse:Alternative branch in if or loop
exceptException handlingExceptionexcept ValueError:Handle specific exceptions
FalseBoolean valueLiteralis_valid = FalseBoolean false value
finallyException handlingExceptionfinally:Code that always executes
forLoop constructControl Flowfor item in list:Iterate over sequences
fromImport statementImportfrom math import sqrtImport specific items from module
globalScope declarationScopeglobal my_varDeclare global variable in function
ifConditionalControl Flowif condition:Basic conditional statement
importModule importImportimport osImport modules or packages
inMembership testOperatorif item in list:Test membership in sequence
isIdentity testOperatorif x is None:Test object identity
lambdaAnonymous functionFunctionlambda x: x * 2Create small anonymous functions
NoneNull valueLiteralresult = NoneRepresents absence of value
nonlocalScope declarationScopenonlocal my_varAccess enclosing scope variable
notLogical operatorOperatorif not condition:Logical NOT operation
orLogical operatorOperatorif x or y:Logical OR operation
passPlaceholderStatementpassEmpty placeholder statement
raiseException raisingExceptionraise ValueError("message")Raise exceptions manually
returnFunction returnStatementreturn resultReturn value from function
TrueBoolean valueLiteralis_valid = TrueBoolean true value
tryException handlingExceptiontry:Begin exception handling block
whileLoop constructControl Flowwhile condition:Create while loops
withContext managerStatementwith open(file) as f:Resource management
yieldGeneratorFunctionyield valueCreate generator functions

Keyword Categories

Control Flow Keywords

Keywords that control the flow of program execution:

  • if, elif, else: Conditional execution
  • for, while: Loop constructs
  • break, continue: Loop control
  • pass: Empty placeholder

Function and Class Definition

Keywords for defining reusable code blocks:

  • def: Function definition
  • class: Class definition
  • lambda: Anonymous functions
  • return: Return values
  • yield: Generator functions

Exception Handling

Keywords for managing errors and exceptions:

  • try, except, finally: Exception handling blocks
  • raise: Manually raise exceptions
  • assert: Debug-time assertions

Import and Module Keywords

Keywords for working with modules:

  • import: Import modules
  • from: Import specific items
  • as: Create aliases

Scope and Variable Keywords

Keywords affecting variable scope:

  • global: Global variable declaration
  • nonlocal: Enclosing scope variable access
  • del: Delete variables or objects

Logical and Comparison Operators

Keywords for logical operations:

  • and, or, not: Logical operators
  • in: Membership testing
  • is: Identity testing

Literal Values

Keywords representing fixed values:

  • True, False: Boolean literals
  • None: Null value literal

Context Management

Keywords for resource management:

  • with: Context manager protocol

Common Usage Patterns

Conditional Execution

# Basic if-elif-else structure
age = 25
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teenager")
else:
    print("Child")

Loop Constructs

# For loop with break and continue
for i in range(10):
    if i == 3:
        continue  # Skip 3
    if i == 7:
        break     # Stop at 7
    print(i)

Exception Handling

try:
    # risky code
except SpecificError as e:
    # handle specific error
except Exception as e:
    # handle general errors
finally:
    # cleanup code

Function Definition

# Function with global variable
counter = 0

def increment():
    global counter
    counter += 1
    return counter

print(increment())  # 1
print(increment())  # 2

Class Definition

class ClassName:
    def __init__(self):
        pass
    
    def method(self):
        return value

Important Notes

  • Case Sensitive: All keywords are lowercase and case-sensitive
  • Reserved: Cannot be used as identifiers (variable names, function names, etc.)
  • Version Specific: Some keywords may be added in newer Python versions
  • Syntax Highlighting: Most editors highlight keywords in different colors
  • Error Prevention: Using keywords as identifiers will raise SyntaxError

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent