Python 3 — Functions & Reusable Code
Writing clean code means avoiding repetitions (the DRY principle: Don't Repeat Yourself). If you write the same calculation code multiple times, wrapping it inside a reusable code machine called a Function is the professional solution.
We declare functions using the def keyword, followed by the function name, parentheses, and a colon. Code inside the function must be indented:
# Defining the function
def say_hello():
print("Welcome back, coder!")
print("Let's write some Python code.")
# Calling the function to execute it
say_hello()
say_hello()
To pass data into a function, put parameter variables inside the parentheses. To send results back from the function, use the return keyword:
# Parameters: num1, num2
def calculate_area(length, width):
area = length * width
return area # Send value back to caller
# Calling function and capturing output
result = calculate_area(5, 10)
print(f"Area: {result}") # Area: 50
Variables created inside a function belong to that function's **local scope** and cannot be read from the outside. Variables declared outside functions exist in the **global scope**:
global_name = "Guido"
def scope_demo():
local_val = 100
print(global_name) # Can read global variables
scope_demo()
# This would crash: print(local_val)
Beginners often confuse print() and return. Printing displays text in the output terminal panel, but doesn't pass the value back to the program. Returning passes the value back to the code, allowing you to store it or do math on it.
Define a function called 'celsius_to_fahrenheit' that accepts a temperature value, converts it using formula (celsius * 9/5) + 32, and returns the result. Call the function with '25' degrees and print the result.