How to write a function
Define and call a function
def creates a function. Its indented body runs only when the function is called.
def greet(name):
return f"Hello, {name}!"
message = greet("Ada")
print(message)
Use parameters and defaults
Parameters receive inputs. A default value makes an argument optional; required parameters must come first.
def calculate_total(price, quantity=1, tax_rate=0.0):
subtotal = price * quantity
return subtotal * (1 + tax_rate)
print(calculate_total(10, quantity=2, tax_rate=0.1))
Return useful values
return ends the call and sends a value back. Without an explicit return, a function returns None.
def divide_with_remainder(number, divisor):
return number // divisor, number % divisor
quotient, remainder = divide_with_remainder(17, 5)
print(quotient, remainder)
Document and scope functions
Local variables exist inside their function. Prefer returning results to modifying global state, and add a concise docstring to reusable functions.
def celsius_to_fahrenheit(celsius):
"""Convert a Celsius temperature to Fahrenheit."""
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
print(celsius_to_fahrenheit(20))