Python ยท Chapter 19 of 45
Python Functions
A function is a reusable block of code defined with `def`. It can take arguments and return a value.
Functions help you avoid repetition and organize your code.
Syntax
def function_name(parameters):
"""Docstring."""
return valueDefining and calling
`def name(params):` defines it. `name(args)` calls it. `return value` sends a result back.
Docstrings
The first string inside a function is its docstring โ used by `help()` and IDEs.
Example 1 (python)
def add(a, b):
return a + b
print(add(3, 5))Output
8Simple two-argument function that returns a sum.
Example 2 (python)
def greet(name="World"):
return f"Hello, {name}!"
print(greet())
print(greet("Sam"))Output
Hello, World!
Hello, Sam!Default argument makes `name` optional.
Key points
- Defined with `def`.
- Parameters go inside `()`.
- `return` sends back a value; without it functions return None.
- Write short, single-purpose functions.
๐ก Note: A function without a `return` statement returns `None` implicitly.
