User-Defined Functions in Python
A user-defined function is a function created by the programmer (not provided by Python).
These functions help in:
✔ Modularizing code
✔ Reusing logic
✔ Improving readability
✔ Reducing program size
✔ Easier debugging and maintenance
Python allows users to define their own functions using the def keyword.
1. What is a User-Defined Function?
A user-defined function is a block of code designed to perform a specific task.
The function executes only when it is called.
Syntax:
def function_name(parameters):
statements
return expression
2. Creating and Calling a Function
Example: simple function
def greet():
print("Hello, welcome to Python!")
greet() # function call
3. Function with Parameters
Parameters allow us to pass values into the function.
def add(a, b):
print(a + b)
add(10, 20)
4. Function with Return Statement
The return statement sends a value back to the caller.
def square(x):
return x * x
result = square(5)
print(result)
5. Types of User-Defined Functions
Python supports many types of functions:
1. Function without parameters and without return value
def show():
print("Hello")
Call:
show()
2. Function with parameters but no return value
def display(name):
print("Hello", name)
3. Function without parameters but with return value
def get_number():
return 10
4. Function with parameters and return value
def multiply(a, b):
return a * b
6. Types of Arguments (Important for Exams)
Python supports several types of arguments:
1. Required Arguments
Correct position and number of arguments are necessary.
def add(a, b):
print(a + b)
add(10, 20) # correct
2. Default Arguments
Provide default value if not passed.
def greet(name="Guest"):
print("Hello", name)
greet() # Hello Guest
greet("John") # Hello John
3. Keyword Arguments
Arguments passed using key=value format, order doesn’t matter.
def info(name, age):
print(name, age)
info(age=25, name="Amit")
4. Variable-Length Arguments (*args)
Accepts multiple positional arguments.
def total(*nums):
print(sum(nums))
total(1, 2, 3, 4)
5. Variable-Length Keyword Arguments (**kwargs)
Accepts multiple keyword arguments.
def details(**data):
for key, value in data.items():
print(key, ":", value)
details(name="John", age=25, city="Delhi")
7. Recursion in User-Defined Functions
A function calling itself is recursive.
Example: factorial
def fact(n):
if n == 0:
return 1
return n * fact(n-1)
print(fact(5))
8. Docstring (Function Documentation)
A docstring describes what the function does.
def greet():
"""This function prints a greeting"""
print("Hello")
To view docstring:
print(greet.__doc__)
9. Scope of Variables (Local vs Global)
Local Variable
Accessible only inside the function.
def func():
x = 10 # local
print(x)
Global Variable
Defined outside any function.
x = 20
def func():
print(x)
Use global keyword to modify global variable in a function:
x = 10
def modify():
global x
x = 50
10. Example Programs Using User-defined Functions
Program 1: Check even or odd
def check(num):
return "Even" if num % 2 == 0 else "Odd"
print(check(7))
Program 2: Find largest of three numbers
def largest(a, b, c):
return max(a, b, c)
print(largest(10, 25, 15))
Program 3: Sum of digits
def sum_digits(n):
total = 0
while n > 0:
total += n % 10
n //= 10
return total
print(sum_digits(123))
11. Advantages of User-Defined Functions
✔ Reusability
✔ Modularity
✔ Easy debugging
✔ Reduced complexity
✔ Improved readability
✔ Less program length
SUMMARY
| Concept | Description |
|---|---|
| UDF | Function created by user |
| Keyword | def |
| Types of functions | No args, with args, returns, no return |
| Arguments | Required, Default, Keyword, *args, **kwargs |
| Return | Sends value back |
| Recursion | Function calling itself |
| Scope | Local & Global variables |
