Reading history

Python Functions: def, Arguments, return and lambda

4 min read 0 views

Learn Python functions: def, parameters, default and keyword arguments, return values, *args, **kwargs, lambda and scope, with examples.

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 return does, 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 def is a docstring. Editors and help(greet) display it.
  • width=1 is 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 return statement returns None.

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']
  • *numbers collects any number of positional arguments into a tuple. With none, the tuple is empty and sum() returns 0.
  • **details collects extra keyword arguments into a dictionary.
  • Returning several values: return a, b returns a tuple, which you can unpack straight into two variables.
  • lambda x: x * x is a small unnamed function made of a single expression. It is most useful as a key for sorted() or as an argument to map().

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

  1. Calling before defining. Python runs top to bottom, so def must run before the call.
  2. Printing instead of returning. If you need the value later, return it.
  3. Mutable default values. def add(item, bag=[]) shares one list across every call. Use bag=None and create the list inside.
  4. Forgetting the parentheses. greet refers 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

  • def defines a function; return sends back a value (otherwise None).
  • Defaults and keyword arguments make calls flexible and readable.
  • *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.
  • lambda creates tiny one-expression functions.

Next: store key/value data with Python Dictionaries.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *