Functions in Python
• What, How, Types, Use Cases
• Prepared by: Assistant Professor Sophie
Angela
• Course: Problem Solving Using Python
Introduction
• Why use functions?
• • Avoid code repetition
• • Improve readability & modularity
• • Easier debugging & maintenance
• • Break large problems into smaller units
What is a Function?
• • Named block of code performing a specific
task
• • Can take inputs (parameters) and return
outputs
• • Defined using def keyword
• • Example: print(), len(), sum()
Defining a Function
• Syntax:
• def function_name(parameters):
• """Optional docstring"""
• statements
• return value (optional)
• Example:
• def greet():
Calling a Function
• To call a function, write its name with
parentheses:
• def greet():
• print('Hello World')
• greet() # Function call
Calling a Function Multiple Times
• Example:
• def say_hello():
• print('Hello from Python function!')
• say_hello()
• say_hello()
• say_hello()
Function with Parameter and
Return
• Example:
• def square(x):
• return x * x
• print(square(3)) # 9
• print(square(5)) # 25
• • 'x' is parameter, 3 and 5 are arguments
Advantages of Functions
• • Code reuse: define once, use many times
• • Abstraction: hides implementation
• • Modularity: easier to organize
• • Maintainability: easier updates
• • Testing: small units are easy to test
Types of Functions
• 1. Built-in: print(), len(), max()
• 2. User-defined: created using def
• 3. Anonymous (lambda): lambda x: x*x
• 4. Recursive: calls itself (e.g., factorial)
More on Function Arguments
• • Positional arguments
• • Keyword arguments
• • Default arguments
• • Variable-length: *args and **kwargs
Example of Default and Variable
Arguments
• def greet(name, msg='Hello'):
• print(f'{msg}, {name}!')
• greet('Alice')
• greet('Bob', msg='Hi')
• def add_all(*nums):
• return sum(nums)
Recursive Function Example
• def factorial(n):
• if n<=1:
• return 1
• else:
• return n * factorial(n-1)
• print(factorial(5)) # 120
Tips for Effective PPT
• • Use readable fonts and large code text
• • Add flow diagrams showing function call →
execution → return
• • Use output screenshots for better clarity
• • Keep slides clean & simple (not text-heavy)
• • Include one exercise slide (e.g., write a
function to find max of 3 numbers)
Summary
• • Function = reusable code block
• • Defined using def, called by name
• • Supports parameters, return values
• • Types: built-in, user-defined, lambda,
recursive
• • Helps modular, readable, efficient coding
References
• • W3Schools – Python Functions
• • Real Python – Defining Functions
• • GeeksforGeeks – Python Functions
• • Programiz – Python Function Tutorial
• • TutorialsPoint – Python Functions