Skip to content
Laviyx Learn

Try

Python course menu

Python Functions: def, Parameters and return Explained Simply

Learn how to write Python functions with def. Understand parameters, arguments, return values, default values, keyword arguments and scope, with clear examples and exercises.

Beginner9 min readUpdated
On this page

A function is a named block of code that does one job. You write it once and then call it whenever you need that job done. You have already used functions that come with Python, like print(), len() and max(). In this lesson you will write your own.

Why use functions?#

  • Avoid repetition: write the logic once, use it many times.
  • Readability: calculate_tax(price) explains itself; ten lines of maths do not.
  • Easier fixes: if the logic has a bug, you fix it in one place.
  • Testing: small functions are easy to check on their own.

Defining and calling a function#

Python
def greet():
    print("Hello!")
    print("Welcome to Laviyx Learn.")

greet()
greet()
Output
Hello!
Welcome to Laviyx Learn.
Hello!
Welcome to Laviyx Learn.
  • def starts a function definition.
  • greet is the function's name (use snake_case, like variables).
  • The parentheses () hold the inputs; this function has none.
  • The colon and the indented block are the function body.

Defining a function does not run it. The code inside only runs when you call it with greet().

Parameters and arguments#

Functions become useful when they accept input. A parameter is a variable listed in the definition. An argument is the actual value you pass in when calling:

Python
def greet(name):          # name is a parameter
    print(f"Hello, {name}!")

greet("Asha")             # "Asha" is an argument
greet("Ravi")
Output
Hello, Asha!
Hello, Ravi!

A function can take several parameters, separated by commas:

Python
def describe(name, city):
    print(f"{name} lives in {city}.")

describe("Meera", "Pune")
Output
Meera lives in Pune.

Returning a value#

print() only shows a value on screen. Usually you want a function to give a value back so the rest of your program can use it. That is what return does:

Python
def add_tax(price, rate):
    return price + price * rate

total = add_tax(200, 0.18)
print(total)
print(add_tax(50, 0.05) * 2)
Output
236.0
105.0

When Python reaches return, the function stops immediately and the value replaces the function call. add_tax(200, 0.18) becomes 236.0.

A function can return early, for example to handle special cases first:

Python
def grade(score):
    if score >= 90:
        return "A"
    if score >= 75:
        return "B"
    if score >= 60:
        return "C"
    return "Needs improvement"

print(grade(95), grade(80), grade(40))
Output
A B Needs improvement

Default parameter values#

Give a parameter a default value with =. Callers can then leave it out:

Python
def add_tax(price, rate=0.18):
    return round(price + price * rate, 2)

print(add_tax(100))         # uses the default rate
print(add_tax(100, 0.05))   # overrides it
Output
118.0
105.0

Parameters with defaults must come after parameters without defaults.

Keyword arguments#

You can name arguments when you call a function. Then their order does not matter, and the call becomes easier to read:

Python
def book_ticket(name, seat, meal="veg"):
    print(f"{name}: seat {seat}, {meal} meal")

book_ticket("Asha", "12A")
book_ticket(seat="3C", name="John", meal="non-veg")
Output
Asha: seat 12A, veg meal
John: seat 3C, non-veg meal

Scope: variables inside functions#

Variables created inside a function are local: they exist only while the function runs and cannot be seen outside it.

Python
def calculate():
    result = 10 * 5
    return result

value = calculate()
print(value)
print(result)   # error
Output
50
NameError: name 'result' is not defined

This is a good thing. It means each function is self-contained, and a variable named total in one function will never clash with a total somewhere else. To get information out of a function, return it.

Documenting a function with a docstring#

A string on the first line of the body is a docstring. It describes what the function does, and tools like editors and help() display it:

Python
def average(numbers):
    """Return the average of a list of numbers."""
    return sum(numbers) / len(numbers)

print(average([4, 8, 9]))
Output
7.0

Common mistakes#

Practice#

Practice exercise

Write a function is_even(number) that returns True if the number is even and False otherwise. Then write a second function count_evens(numbers) that uses is_even to return how many even numbers are in a list.

Test it with:

Python
print(is_even(10))
print(count_evens([1, 2, 3, 4, 10, 15]))
Show hint

A number is even when number % 2 == 0. That comparison already gives True or False, so you can return it directly. In count_evens, loop over the list and add 1 to a counter whenever is_even returns True.

Show solution
Python
def is_even(number):
    """Return True if number is even."""
    return number % 2 == 0


def count_evens(numbers):
    """Return how many even numbers the list contains."""
    count = 0
    for n in numbers:
        if is_even(n):
            count += 1
    return count


print(is_even(10))
print(count_evens([1, 2, 3, 4, 10, 15]))
Output
True
3

The even numbers in the list are 2, 4 and 10. Notice how count_evens reads almost like English because is_even has a clear name.

Key takeaway#

Finished this lesson?