- Define and call functions with
defand return values withreturn. - Use positional, keyword, default,
*argsand**kwargsarguments. - Explain local and global scope.
- Write lambda functions and simple recursive functions.
What is a Function?
- A function is a named, reusable block of code that performs a specific task. It runs only when it is called.
- Benefits: reusability (write once, use many times), modularity (break a big problem into small parts), easier testing and readability.
- Built-in functions come with Python (
print(),len(),max()); user-defined functions are written withdef.
def area_of_rectangle(length, width):
"""Return the area of a rectangle."""
return length * width
result = area_of_rectangle(8, 5)
print("Area:", result)
print(area_of_rectangle.__doc__)Area: 40 Return the area of a rectangle.
Parameters are the names in the definition (length, width); arguments are the actual values passed in the call (8, 5).
Return Values
returnends the function and sends a value back to the caller.- A function without
return(or with a barereturn) returnsNone. - A function can return several values as a tuple.
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([12, 4, 25, 9])
print(low, high)
def greet(name):
print("Hello", name) # prints, but returns nothing
value = greet("Kiran")
print(value)4 25 Hello Kiran None
Types of Arguments
| Type | Description |
|---|---|
| Positional | Matched to parameters by their order. |
| Keyword | Passed as name=value; order does not matter. |
| Default | Parameter has a default value used when the argument is omitted. |
*args | Collects any number of extra positional arguments into a tuple. |
**kwargs | Collects any number of extra keyword arguments into a dictionary. |
def make_bill(item, price, qty=1, discount=0):
return f"{item}: {price * qty - discount}"
print(make_bill("Pen", 10)) # positional + defaults
print(make_bill("Book", 250, qty=2)) # keyword argument
print(make_bill(price=40, item="Ink", discount=5))
def total(*args):
return sum(args)
print(total(1, 2, 3, 4))
def profile(**kwargs):
for key, value in kwargs.items():
print(key, "=", value)
profile(name="Asha", city="Bhopal")Pen: 10 Book: 500 Ink: 35 10 name = Asha city = Bhopal
None and create the list inside the function.def add_item_wrong(item, basket=[]):
basket.append(item)
return basket
print(add_item_wrong("a"))
print(add_item_wrong("b")) # the same list is reused!
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket
print(add_item("a"))
print(add_item("b"))['a'] ['a', 'b'] ['a'] ['b']
Scope: Local and Global Variables
- A variable created inside a function is local – it exists only while the function runs.
- A variable created outside all functions is global – it can be read inside functions.
- To assign to a global variable inside a function, declare it with
global. Python looks up names in the order Local → Enclosing → Global → Built-in (LEGB).
counter = 0 # global
def increase():
global counter
counter += 1
def show():
message = "local text" # local
print(message, counter)
increase()
increase()
show()local text 2
Lambda Functions
A lambda is a small anonymous function written in one expression: lambda parameters: expression. It is often passed to functions such as sorted(), map() and filter().
square = lambda x: x * x
print(square(6))
nums = [5, 12, 7, 20]
print(list(map(lambda n: n * 2, nums)))
print(list(filter(lambda n: n > 6, nums)))
students = [("Asha", 82), ("Ravi", 67), ("Meera", 91)]
print(sorted(students, key=lambda s: s[1], reverse=True))36
[10, 24, 14, 40]
[12, 7, 20]
[('Meera', 91), ('Asha', 82), ('Ravi', 67)]Recursion
A recursive function calls itself. Every recursive function needs a base case that stops the recursion; otherwise Python raises RecursionError (the default depth limit is about 1000 calls).
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(factorial(5))
print([fibonacci(i) for i in range(10)])120 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Key Takeaways
- Define with
def, call withname(args); no return meansNone. *args→ tuple,**kwargs→ dict; avoid mutable default values.- Names resolve by LEGB; recursion needs a base case.
Video : Functions
Question / Answer (15 questions)
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.
- Python Software Foundation. (n.d.). More Control Flow Tools. In The Python Tutorial. https://docs.python.org/3/tutorial/controlflow.html
- Python Software Foundation. (n.d.). Execution Model (Naming and Binding). In The Python Language Reference. https://docs.python.org/3/reference/executionmodel.html
- Python Software Foundation. (n.d.). Built-in Functions. The Python Standard Library. https://docs.python.org/3/library/functions.html
- Goodger, D., & van Rossum, G. (2001). PEP 257 – Docstring Conventions. Python Enhancement Proposals. https://peps.python.org/pep-0257/
- Python Software Foundation. (n.d.). Glossary. Python 3 Documentation. https://docs.python.org/3/glossary.html
- Lutz, M. (2013). Learning Python (5th ed.). O’Reilly Media.
- Downey, A. B. (2024). Think Python (3rd ed.). O’Reilly Media. (Free online edition by Green Tea Press.) https://allendowney.github.io/ThinkPython/