Defining Functions
beginner12 min readLesson 24 of 169
def, parameters, calling, and return โ functions that give answers.
A function is a named, reusable block of code:
def greet(name):
print(f"Hello, {name}!")
greet("Minh") # Hello, Minh!
greet("Lan") # Hello, Lan!
Anatomy: def starts the definition; the name follows the same rules as
variables; parameters (name) are inputs the function receives; the body
is indented under the def line. Defining does not run the code โ calling
does.
Why functions exist
- Reuse: write once, call anywhere.
- Naming:
send_report()documents intent better than 30 loose lines. - Testing: a function is a unit you can check in isolation.
- Decomposition: big problems become small named steps.
return: produce a result
print shows a human something; return hands a value back to the program:
def add(a, b):
return a + b
total = add(2, 3) # total is now 5
print(add(10, 5) * 2) # return values compose into expressions
return also exits the function immediately. A function with no return
statement returns None.