A function is a named block of code that you write once and call whenever you need it. Functions keep programs short, make them easier to test, and let you give a clear name to each job. This lesson covers def, parameters, default values, keyword arguments, return, *args, **kwargs and lambda functions.
In this lesson you will learn
- How to define and call a function
- Positional, keyword and default arguments
- What
returndoes, and what a function returns without it - How to accept any number of arguments
- When to use a
lambda
Defining and Calling Functions
def greet(name):
"""Return a friendly greeting."""
return f"Hello, {name}!"
def area(length, width=1):
return length * width
print(greet("Tania"))
print(area(5, 3))
print(area(5)) # width uses its default
print(area(width=2, length=7))
def no_return():
print("This function returns nothing")
result = no_return()
print("Result is", result)
Output
Hello, Tania!
15
5
14
This function returns nothing
Result is None
def name(parameters):starts a function. The indented lines are its body.- The triple-quoted line under
defis a docstring. Editors andhelp(greet)display it. width=1is a default value, used when the caller leaves the argument out.area(width=2, length=7)uses keyword arguments, so their order does not matter.- A function without a
returnstatement returnsNone.
Parameter or argument?
A parameter is the name in the definition (length). An argument is the actual value passed in the call (5).
*args, **kwargs, Multiple Returns and Lambda
def total(*numbers):
return sum(numbers)
def profile(name, **details):
print(name, details)
print(total(2, 4, 6))
print(total())
profile("Arif", city="Sylhet", age=24)
def min_max(values):
return min(values), max(values) # returns a tuple
low, high = min_max([7, 2, 9, 4])
print("Low:", low, "High:", high)
square = lambda x: x * x
print(list(map(square, [1, 2, 3])))
print(sorted(["pear", "fig", "banana"], key=lambda w: len(w)))
Output
12
0
Arif {'city': 'Sylhet', 'age': 24}
Low: 2 High: 9
[1, 4, 9]
['fig', 'pear', 'banana']
*numberscollects any number of positional arguments into a tuple. With none, the tuple is empty andsum()returns 0.**detailscollects extra keyword arguments into a dictionary.- Returning several values:
return a, breturns a tuple, which you can unpack straight into two variables. lambda x: x * xis a small unnamed function made of a single expression. It is most useful as akeyforsorted()or as an argument tomap().
Local and Global Variables
A variable created inside a function is local: it exists only while the function runs. Code inside a function can read variables defined outside it, but assigning to that name creates a new local variable instead. Pass values in as arguments and send results back with return, rather than changing global variables.
Common Mistakes
- Calling before defining. Python runs top to bottom, so
defmust run before the call. - Printing instead of returning. If you need the value later,
returnit. - Mutable default values.
def add(item, bag=[])shares one list across every call. Usebag=Noneand create the list inside. - Forgetting the parentheses.
greetrefers to the function;greet("Ali")calls it.
Practice Exercises
Exercise 1. Write is_even(n) that returns True or False.
Show answer
def is_even(n):
return n % 2 == 0
print(is_even(10), is_even(7)) # True False
Exercise 2. Write average(*nums) that returns 0 when no numbers are given.
Show answer
def average(*nums):
return sum(nums) / len(nums) if nums else 0
print(average(4, 8, 6), average()) # 6.0 0
Frequently Asked Questions
Can a Python function return more than one value?
Yes. return a, b returns a tuple, and the caller can unpack it with x, y = f().
What is the difference between a lambda and a normal function?
A lambda is a single expression with no name and no statements. Use def for anything longer than one simple expression.
Are arguments passed by value or by reference?
Python passes references to objects. A function can change a list you pass in (for example with append), but assigning a new value to the parameter does not affect the caller’s variable.
Summary
defdefines a function;returnsends back a value (otherwiseNone).- Defaults and keyword arguments make calls flexible and readable.
*argscollects extra positional arguments into a tuple;**kwargscollects extra keyword arguments into a dict.lambdacreates tiny one-expression functions.
Next: store key/value data with Python Dictionaries.
