Functions
Define, call, and return values from functions so you can reuse clear pieces of code.
Your first function
A function is a named, reusable piece of code. You define it once, then call it whenever you need it.
Use def to define a function. The indented lines are its body.
def function_name(parameter):
# code to run
return value
function_name(argument)
def greet(name):
"""Print a friendly greeting."""
print(f"Hello, {name}!")
greet("Mina")
name is a parameter: a name in the function definition. "Mina" is an argument: the actual value you pass when calling the function.
The string under the definition is a docstring. It briefly tells readers what the function does.
Return a result
def add(left, right):
return left + right
result = add(3, 4)
print(result)
return sends a value back to the code that called the function. Here, add(3, 4) produces 7, which is stored in result.
Returning multiple values
def split_full_name(full_name):
"""Return the first and last parts of a name."""
first, last = full_name.split()
return first, last
first_name, last_name = split_full_name("Ada Lovelace")
print(first_name)
print(last_name)
Key points
- Define a function with def and a name.
- Call a function with parentheses.
- Parameters receive arguments passed to a call.
- Use return to send a result back.
- Docstrings explain what a function does.
Worked example
A grocery app converts taka to dollars in many places — write the conversion ONCE as a function and reuse it.
def tk_to_usd(taka, rate=110):
return round(taka / rate, 2)
print(tk_to_usd(550))
print(tk_to_usd(550, 100))
How it works, step by step
- def names the function and lists its parameters.
- return hands the result back to whoever called it.
- rate=110 is a default: callers may omit it (first call) or override it (second call).
References & Further Reading
Related entries from PyLabs's own reference library.
- callable() (Check whether an object can be called with parentheses.)
- help() (Open Python's built-in help system for a topic.)
Practice exercise
Not passed yetWrite a function named square that accepts one number and returns its square. Call it with 3 and print the result.
Expected output: 9
# Write your code below
Check yourself
Functions quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.