Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Python notes · Topic 10 of 22 · 5 min read

Python functions

Python functions notes with examples: def and return, default and keyword arguments, *args and **kwargs, local and global scope, lambda and recursion.

A function is a machine: inputs in, answer out

A function is a named block of code you can run whenever you need it. You have already used built-in functions such as print(), len() and input(). Now you will write your own.

Functions help you avoid repeating code, give a name to an idea, and test one piece at a time.

Defining and calling a function

def greet(name):                 # define: 'name' is a parameter
    print("Hello,", name)

greet("Asha")                    # call: "Asha" is the argument
greet("Ravi")
  • def, the function name, brackets and a colon start the definition.
  • The body is indented.
  • Defining a function does nothing on its own. The code runs only when you call it.

return: send a value back

def gst(amount, rate=18):
    return amount * rate / 100

tax = gst(1000)
print(tax)            # 180.0
print(gst(500, 5))    # 25.0

return ends the function and hands the value back to the caller, who can store it, print it or use it in a calculation. A function without return gives back None.

print versus return

print() shows a value on the screen; return gives the value to the code that called the function. If a function only prints, you cannot use its answer in a calculation.

What happens when you call a function

  1. Python jumps to the function and copies each argument into its parameter.
  2. The body runs line by line.
  3. At return (or the end), Python jumps back to where the call was made, carrying the result.

Default values and keyword arguments

def emi(principal, rate=10, years=1):
    months = years * 12
    r = rate / 12 / 100
    return principal * r * (1 + r) ** months / ((1 + r) ** months - 1)

emi(100000)                       # uses rate=10, years=1
emi(100000, years=3)              # keyword argument: skip rate, set years
emi(principal=50000, rate=9)

Parameters with defaults must come after those without: def f(a, b=2) is fine, def f(a=1, b) is a SyntaxError.

*args and **kwargs

def total(*nums):                  # any number of positional arguments, as a tuple
    return sum(nums)

total(5, 10, 15)                   # 30

def profile(**info):               # any number of keyword arguments, as a dict
    for key, value in info.items():
        print(key, "=", value)

profile(name="Asha", city="Ranchi")

Local and global variables

A variable created inside a function is local: it exists only while the function runs.

def add_bonus(marks):
    bonus = 5                 # local
    return marks + bonus

add_bonus(80)
print(bonus)                  # NameError: bonus only lived inside the function

A variable created outside every function is global. A function can read it, but to change it the function must say global name. It is usually better to pass values in and return results instead of changing globals.

lambda and docstrings

A lambda is a small one-line function without a name, mostly used as a key for sorting:

square = lambda x: x * x
students = [("Asha", 91), ("Ravi", 78)]
students.sort(key=lambda s: s[1], reverse=True)

A docstring is a string on the first line of a function that explains it. help(function) shows it.

def area(length, width):
    """Return the area of a rectangle."""
    return length * width

Recursion: a function that calls itself

def factorial(n):
    if n <= 1:              # base case: stops the recursion
        return 1
    return n * factorial(n - 1)

print(factorial(5))         # 120

Every recursive function needs a base case. Without one, it calls itself until Python stops it with a RecursionError.

Example: password strength checker

def strength(pw):
    score = 0
    if len(pw) >= 8:
        score += 1
    if any(c.isdigit() for c in pw):
        score += 1
    if any(c.isupper() for c in pw):
        score += 1
    return ["Weak", "Weak", "Medium", "Strong"][score]

print(strength("hello"))        # Weak
print(strength("Hello2026"))    # Strong

Common mistakes

  • Forgetting the brackets when calling: greet names the function; greet() runs it.
  • Printing inside a function when the caller needs the value returned.
  • Code after return in the same block: it never runs.
  • Using a mutable default like def f(items=[]): the same list is shared between calls. Use items=None.

Key points

  • def name(parameters): defines a function; name(arguments) calls it.
  • return sends a value back; without it the function returns None.
  • Defaults and keyword arguments make calls flexible; *args and **kwargs accept any number of arguments.
  • Variables inside a function are local. Recursion needs a base case.

Practice questions

1. Write a function is_even(n) that returns True or False.
def is_even(n):
    return n % 2 == 0
2. What does this print?
def f(x):
    x = x + 1
    return x * 2
print(f(3))

8. Inside the function x becomes 4, and 4 * 2 is 8.

3. Write a function that returns the average of any number of marks.
def average(*marks):
    return sum(marks) / len(marks)

print(average(80, 90, 70))   # 80.0
4. Write a recursive function for the sum of the digits of a number.
def digit_sum(n):
    if n < 10:
        return n
    return n % 10 + digit_sum(n // 10)
5. What does a function return if it has no return statement?

None.