Syntax & Indentation
Overview
Python's most famous characteristic is its use of significant whitespace. Instead of using curly braces {} or keywords to define the start and end of functions, loops, and classes, Python relies entirely on indentation. This design choice forces developers to write code that is visually structured and easy to read. PEP 8, the official Python style guide, dictates that you should use exactly 4 spaces per indentation level. Colons (:) are used to declare the start of an indented block.
Syntax
def evaluate_temperature(temp):
# The colon indicates the start of a block.
# Everything indented below it belongs to this function.
if temp > 30:
print("It's a hot day") # Indented 4 spaces
if temp > 40:
print("Stay indoors!") # Indented 8 spaces
elif temp < 10:
print("It's quite cold")
else:
print("Perfect weather")Common Pitfalls
- Mixing tabs and spaces. This is a fatal error in Python 3 (IndentationError). Always configure your code editor to replace tabs with 4 spaces.
- Forgetting the colon
:at the end ofif,else,for,while,def, orclassstatements. This will result in a SyntaxError.
Interview Questions
Python uses lexical scoping based purely on indentation levels. When the indentation level decreases, the current block is considered closed, and execution returns to the outer scope.
Real-World Example
Cleanly nesting logic using strict indentation for a user authentication check.
def login_user(username, password, db):
if db.user_exists(username):
user = db.get_user(username)
if user.check_password(password):
if user.is_active:
return "Login Successful"
else:
return "Account Suspended"
else:
return "Invalid Password"
return "User Not Found"Check Your Knowledge
Test your understanding of Syntax & Indentation with these quick questions.