Why this matters
When the same steps appear again and again, you wrap them in a function and give them a name. Then you can run those steps any time just by calling the name, with different inputs each time. Functions keep programs short, clear, and reusable.
The idea
You define a function with def, list its arguments in parentheses, and send a
result back with return:
def function_name(argument1, argument2):
# process
return result
- Arguments are the inputs the function receives.
returnhands a return value back to the caller; the function stops there.- Calling the function means writing its name with values in parentheses, e.g.
area(10, 5).
Python already gives you built-in functions like print(); the ones you write
yourself are user-defined functions.
Picture it
flowchart TD A([Call area with 10, 5]) --> B[base = 10, height = 5] B --> C[S = base * height / 2] C --> D[return S] D --> E([caller receives 25.0])
Worked example
def area(base, height):
s = base * height / 2
return s
print(area(10, 5)) # 25.0
print(area(6, 7)) # 21.0
The arguments 10 and 5 flow into base and height. The function computes s and
returns it, so print shows 25.0. Call it again with new values and you get a new result.
Your turn
Write functions that take arguments and return a computed value, and predict what a function call prints.
Recap
def name(args):defines a function;returnsends back the return value.- Arguments are inputs; calling runs the function with real values.
print()is a built-in function; the ones you write are user-defined.