A function is a block of code that runs only when you call it. Functions let you write code once and use it many times, which keeps programs short and easy to fix. In this lesson you will learn how to define functions, pass arguments, return values, and use default, keyword and variable-length arguments, with output for every example.

Try every example in our online Python compiler.

 

Define and call a function

Use the def keyword, then the function name, round brackets and a colon. The code inside is indented.

def greet(name):
    print('Hello,', name)

greet('Asha')

Output:

Hello, Asha

name is a parameter (the name in the definition), and ‘Asha’ is an argument (the value you pass when you call the function).

 

Return a value

A function can send a result back with return.

def add(a, b):
    return a + b

result = add(3, 4)
print(result)

Output:

7

If a function has no return statement, it returns None.

def no_return():
    pass

print(no_return())
None

Default arguments

Give a parameter a default value, and the argument becomes optional.

def power(base, exp=2):
    return base ** exp

print(power(5))
print(power(2, 3))

Output:

25
8

Keyword arguments

You can pass arguments by name, in any order.

def intro(name, age):
    print(name, 'is', age)

intro(age=20, name='Ravi')

Output:

Ravi is 20

Any number of arguments: *args and **kwargs

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.

def total(*numbers):
    return sum(numbers)

print(total(1, 2, 3))
print(total(10, 20))

def show(**info):
    for key, value in info.items():
        print(key, '=', value)

show(name='Asha', city='Pune')

Output:

6
30
name = Asha
city = Pune

Return more than one value

A function can return several values as a tuple, and you can unpack them.

def min_max(values):
    return min(values), max(values)

low, high = min_max([4, 9, 1])
print(low, high)

Output:

1 9

Variable scope

A variable created inside a function is local, and it exists only in that function.

x = 10

def f():
    x = 5
    print('inside', x)

f()
print('outside', x)

Output:

inside 5
outside 10

To change a global variable inside a function, declare it with the global keyword. Use this sparingly, because it makes code harder to follow.

counter = 0

def inc():
    global counter
    counter += 1

inc()
inc()
print(counter)

Output:

2

Docstrings

A string on the first line of a function describes it.

def area(r):
    '''Return the area of a circle.'''
    return 3.14159 * r * r

print(area(2))
print(area.__doc__)

Output:

12.56636
Return the area of a circle.

Lambda functions

A lambda is a short, nameless function written in one line.

square = lambda n: n * n
print(square(6))
print(list(map(lambda n: n * 2, [1, 2, 3])))

Output:

36
[2, 4, 6]

Recursion

A function can call itself. This is called recursion. It needs a base case to stop.

def fact(n):
    if n <= 1:
        return 1
    return n * fact(n - 1)

print(fact(5))

Output:

120

Common mistakes

1. Forgetting return. If you print inside a function but do not return, you cannot use the result later. The function gives None.

2. Using a list as a default argument. The default list is created once and shared between calls.

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item(1), add_item(2))
[1, 2] [1, 2]

Both calls changed the same list. Use None as the default instead:

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item(1), add_item(2))
[1] [2]

3. Calling a function before it is defined. Define the function above the line that calls it.

 

Practice questions

  1. Write a function is_even(n) that returns True for even numbers.
  2. Write a function that returns the area of a rectangle, with a default width of 1.
  3. Write a function that accepts any number of values and returns their average.
  4. Write a function that returns the largest and smallest values of a list.

Answers

def is_even(n):
    return n % 2 == 0

print(is_even(4), is_even(7))     # True False

Summary

  • Define a function with def, and call it by name with brackets.
  • Use return to send a value back, and parameters to receive values.
  • Default, keyword, *args and **kwargs make functions flexible.
  • Variables created inside a function are local.