Function body ¶
In Python, the function body is the code that runs when the function is called. It must be indented to show it belongs to the function.
Indentation Rules ¶
- Use exactly 4 spaces for indentation (not tabs).
- Every line of the function's code must be indented at the same level.
- Python uses indentation to understand what code belongs to the function.
def calculate_area(length, width):
area = length * width # Indented with 4 spaces
return area # Also indented with 4 spaces
def bad_indentation(x):
print("Three spaces") # ❌ Wrong: Only 3 spaces
print("Five spaces") # ❌ Wrong: 5 spaces
print("No spaces") # ❌ Wrong: Not indented at all
Multiple Lines in Function Body ¶
All related code must be indented:
def calculate_total_price(price, tax_rate):
# Everything indented belongs to the function
subtotal = price
tax = price * tax_rate
total = subtotal + tax
return total
Nested Indentation ¶
When you have loops or if-statements inside a function, they get an additional level of indentation:
def process_numbers(numbers):
total = 0 # First level: 4 spaces
for number in numbers: # First level: 4 spaces
if number > 0: # Second level: 8 spaces
total += number # Third level: 12 spaces
return total # Back to first level
The
return
statement
¶
A function can send back (or "return") a value to whoever called it using the
return
statement.
Think of it like a function completing its task and reporting back with the result.
Basic Return Usage ¶
def calculate_area(length, width):
area = length * width
return area # Sends the calculated area back
What Can Be Returned? ¶
Functions can return any type of data:
def get_pi():
return 3.14159 # Returns a number
def get_greeting():
return "Hello!" # Returns a string
def get_coordinates():
return [10, 20] # Returns a list
def is_adult(age):
return age >= 18 # Returns a boolean
Early Returns ¶
A function stops executing when it hits a
return
:
def check_temperature(temp):
if temp > 100:
return "Too hot!" # Function ends here if temp > 100
if temp < 0:
return "Too cold!" # Function ends here if temp < 0
return "Just right!" # Only reaches here if temp is 0-100
No Return Statement ¶
If a function doesn't have a
return
statement, it returns
None
by default:
def greet(name):
print(f"Hello, {name}") # Prints something but returns None
result = greet("Alice")
print(result) # Prints: None
Common Return Mistakes ¶
# ❌ Unreachable code after return
def bad_function():
return "Hello"
print("This never runs!") # This line will never execute
# ❌ Forgetting to return
def calculate_sum(a, b):
total = a + b # Calculates but doesn't return!
# Should be: return total
# ✅ Correct usage
def calculate_sum(a, b):
total = a + b
return total # Returns the result