Understanding and Applying Proper Indentation in Python
Python uses indentation to define blocks of code instead of braces or keywords. Proper indentation is mandatory; incorrect indentation causes IndentationError
or changes program behavior.
if
, for
, while
, def
, and class
.def greet(name):
if name:
print(f"Hello, {name}!")
else:
print("Hello, stranger!")
greet("Alice")
def greet(name):
if name: # IndentationError: expected an indented block
print(f"Hello, {name}!")
else:
print("Hello, stranger!")
greet("Alice")
def foo():
↹print("Hello") # Tab
print("World") # Spaces
# This will raise:
# TabError: inconsistent use of tabs and spaces in indentation
python -m tabnanny your_script.py
to detect inconsistent indentation.Indented blocks define the body of functions, loops, conditionals, and classes. Example:
for i in range(3):
print(i)
if i == 1:
print("One")
print("Done") # This line is outside the loop
Output:
0
1
One
2
Done