LearnFrenzy
Sign in Take a free test

Python Programming · Topic 11 of 25

Functions Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Functions · Study material

A function packages a piece of logic under a name, so it can be reused, tested and read in isolation. Every real Python program is built from functions – and functions are where Python's most-asked interview questions live: the mutable default argument, *args and **kwargs, why a function without return gives None, global vs nonlocal, and whether Python passes by value or by reference. This topic covers all of them, then 50 practice questions run on Python 3.

On this page

  • def, return and the implicit None
  • Positional, keyword and default arguments
  • The mutable default argument trap
  • *args, **kwargs and argument unpacking
  • Keyword-only and positional-only parameters
  • Scope (LEGB), global, nonlocal and how arguments are passed

Defining and calling functions

def name(parameters): creates a function; the indented body runs only when it is called. return value sends a result back and ends the function immediately. A function that reaches its end without return (or with a bare return) returns None. A string as the first statement is the function's docstring.

def area(length, width):
    """Return the area of a rectangle."""
    return length * width            # return sends a value back and ends the function

def greet(name):
    print(f"Hello, {name}!")         # no return statement …

print(area(4, 5))
result = greet("Asha")               # … so the call evaluates to None
print(result)
print(area.__doc__)

Output

20
Hello, Asha!
None
Return the area of a rectangle.

Positional, keyword and default arguments

Parameters are the names in the definition; arguments are the values in the call. Arguments are matched by position, or by name with name=value (keyword arguments, in any order). A parameter with a default value becomes optional. Rules: parameters with defaults must come after those without, and in a call, positional arguments must come before keyword arguments.

def ticket(name, seat, cls="Economy", meal=True):
    return f"{name} | seat {seat} | {cls} | meal: {meal}"

print(ticket("Asha", "12A"))                       # positional; defaults used
print(ticket("Ravi", "3C", "Business"))            # third argument by position
print(ticket(seat="7F", name="Meera", meal=False)) # keyword arguments: any order

Output

Asha | seat 12A | Economy | meal: True
Ravi | seat 3C | Business | meal: True
Meera | seat 7F | Economy | meal: False

The mutable default argument trap

Default values are evaluated once, when the def statement runs – not on every call. A mutable default such as [] or {} is therefore shared by every call that uses it, and keeps growing. Use None as the default and create the object inside the function.

def add_item(item, cart=[]):        # ✘ the default list is created ONCE, when def runs
    cart.append(item)
    return cart

print(add_item("pen"))
print(add_item("book"))              # the same list again!

def add_item_fixed(item, cart=None): # ✔ use None and create a new list inside
    if cart is None:
        cart = []
    cart.append(item)
    return cart

print(add_item_fixed("pen"))
print(add_item_fixed("book"))

Output

['pen']
['pen', 'book']
['pen']
['book']

*args, **kwargs and unpacking

*args collects any extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. In a call, the same symbols do the reverse: f(*seq) spreads a sequence into positional arguments and f(**mapping) spreads a dict into keyword arguments.

def average(*marks):                    # *args: extra positional arguments, as a tuple
    return sum(marks) / len(marks) if marks else 0

def profile(name, **details):           # **kwargs: extra keyword arguments, as a dict
    extras = ", ".join(f"{k}={v}" for k, v in details.items())
    return f"{name} ({extras})"

print(average(70, 80, 90), average())
print(profile("Asha", city="Pune", age=20))

scores = [60, 75, 90]
info = {"city": "Delhi", "branch": "CSE"}
print(average(*scores))                 # * unpacks a list into positional arguments
print(profile("Ravi", **info))          # ** unpacks a dict into keyword arguments

Output

80.0 0
Asha (city=Pune, age=20)
75.0
Ravi (city=Delhi, branch=CSE)

Keyword-only and positional-only parameters

Parameters after a bare * (or after *args) must be passed by keyword – good for flags such as fee= that should be explicit. Parameters before a / (Python 3.8+) must be passed by position. The full order is: positional-only, /, normal, *args or *, keyword-only, **kwargs.

def transfer(amount, /, to, *, fee=0, note=""):
    # amount: positional-only (before /);  to: either way;  fee, note: keyword-only (after *)
    return f"{amount} to {to}, fee {fee}{', ' + note if note else ''}"

print(transfer(500, "Ravi"))
print(transfer(500, to="Meera", fee=5, note="rent"))
try:
    transfer(500, "Ravi", 5)             # fee cannot be passed by position
except TypeError as e:
    print("TypeError:", e)

Output

500 to Ravi, fee 0
500 to Meera, fee 5, rent
TypeError: transfer() takes 2 positional arguments but 3 were given

Scope: local, global and nonlocal

Names are looked up in the LEGB order: Local, Enclosing function, Global (module), Built-in. Assigning to a name inside a function makes it local to that function – for the whole function, which is why reading it before the assignment raises UnboundLocalError. Declare global name to assign to a module variable and nonlocal name to assign to a variable of an enclosing function (closures). Prefer returning values over modifying globals.

rate = 0.18                       # global (module) variable

def price_with_tax(price):
    tax = price * rate            # reading a global is fine
    return price + tax            # tax is LOCAL: it disappears after the call

visits = 0
def record_visit():
    global visits                 # needed to ASSIGN to a global
    visits += 1

def make_counter():
    count = 0                     # enclosing-function variable
    def counter():
        nonlocal count            # needed to assign to the enclosing variable
        count += 1
        return count
    return counter

print(price_with_tax(100))
record_visit(); record_visit()
print(visits)
c = make_counter()
c(); c()
print(c())

Output

118.0
2
3

How arguments are passed

Python passes references to objects ("pass by object reference" or "call by sharing"). The parameter is a new name for the caller's object: mutating a mutable object (list, dict) is visible to the caller, but rebinding the parameter, or "changing" an immutable object such as an int or str, is not.

def update(scores, bonus):
    scores.append(100)        # changes the caller's list (same object)
    bonus += 5                # rebinds the LOCAL name only
    scores = [0]              # rebinding the parameter does not affect the caller

marks = [70, 80]
extra = 10
update(marks, extra)
print(marks, extra)

Output

[70, 80, 100] 10

Common mistakes

  • Forgetting return – the function gives None.
  • print instead of return – the value cannot be used by the caller.
  • Mutable default arguments – use None.
  • Default before non-default – def f(a=1, b) is a SyntaxError.
  • count += 1 on a global without global – UnboundLocalError.
  • Passing an argument twice – by position and by keyword: TypeError.
  • Calling a function before its def has run – NameError.

Key points to remember

  • No return means the call returns None.
  • Defaults are evaluated once, at definition time.
  • *args is a tuple; **kwargs is a dict.
  • After * keyword-only; before / positional-only.
  • Assignment makes a name local unless declared global or nonlocal.
  • Arguments are passed as object references.
  • Functions are objects: pass them, store them, return them.

Frequently asked questions

Is Python pass-by-value or pass-by-reference?

Neither exactly: it passes object references by value. Mutations of a shared mutable object are visible; rebinding a parameter is not.

Can a function return several values?

It returns one tuple: return a, b – which the caller can unpack with x, y = f().

What are type hints for?

def area(l: float, w: float) -> float documents the expected types for readers, IDEs and checkers like mypy; Python does not enforce them at run time.

Where can I learn more?

Read Python Functions, Python Function Arguments and Scope, Lambda and Recursion in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links