Lesson · Python for Beginners
Functions and parameters
Functions name a task and let a program use it with different values.
What you will learn
- Define and call a function
- Pass an argument to a parameter
- Return a value to the caller
Define, then call
A function definition begins with def, a name, parentheses, and a colon. Its indented body runs only when the function is called. Defining a function near the top of a script does not itself perform the task, so a program must call it in the order needed.
Parameters make functions reusable
A parameter is a name in the function definition; an argument is the value supplied by a call. The function can use the parameter without knowing which specific value the caller will provide. Choose parameter names that describe the expected information and keep each function focused on one coherent job.
Return data instead of printing
return sends a result back to the code that called the function. print displays text to a person but does not provide that text as a reusable calculation result. Returning values makes it possible to test a function, combine it with other operations, and decide separately when or how to display the result.
Keep scope in mind
A parameter and a name assigned inside a function are local to that function unless explicitly returned or otherwise shared. The caller should not rely on a local name existing outside the function. This boundary helps a function behave predictably when used from different parts of a program.
def rectangle_area(width, height):
return width * height
area = rectangle_area(4, 3)
print(area)
Expected output
12
Practice exercise
Write a function that accepts a name and returns a greeting string.
Show a hint
Use an f-string in the return statement, then print the call result.
Show one possible solution
def greet(name): return f'Hello, {name}!'; print(greet('Ravi')) prints Hello, Ravi!.
Quick check
Returning and printing are different operations; the caller can use a returned value.