1. The Lexical Significance of Whitespace
INDENT and DEDENT Tokens in the Lexer
- In Python, indentation is not a cosmetic styling choice; it is a syntactical requirement enforced by the CPython parser.
- When the Python lexical analyzer scans source code, it generates INDENT and DEDENT tokens whenever the leading whitespace on a newline increases or decreases.
- Standard PEP 8 convention dictates using exactly 4 spaces per indentation level. Never mix physical TAB characters with spaces in Python 3, which raises a TabError.
def calculate_grade(score):
# 4 spaces indentation creates a function block
if score >= 90:
# 8 spaces creates a nested conditional block
grade = "A"
else:
grade = "B"
return grade
print("Grade for 95:", calculate_grade(95))