Skip to content

Functions

Define, call, and return values from functions so you can reuse clear pieces of code.

10 min read 10 quiz questions

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)
Example 1: Define and call a function
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

Example 2: Return a value
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

Example 3: Return 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.

Example
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

  1. def names the function and lists its parameters.
  2. return hands the result back to whoever called it.
  3. 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.)

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Practice exercise

Not passed yet

Write 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
Want another challenge on this module? More coding practice

Check yourself

Functions quiz

10 questions. You get instant feedback per question, and the timer starts when you press the button.

Lesson incomplete

Not completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/5 complete
Module cheat sheet