Unit 3 -Functions
A function is a block of organized and
reusable program code that performs a
specific, single, and well-defined task.
A function provides an interface for
communication in terms of how
information is transferred to it and how
results are generated.
CS25C05 - PROBLEM SOLVING AND
PYTHON PROGRAMMING- UNIT 3
2.
Introduction to Functions
-A function is a reusable block of code designed to perform a
specific task.
- Enhances modularity, readability, and reusability.
- Types:
- Built-in functions (e.g., print(), len())
- User-defined functions (using def keyword)
def wish():
print('Hello, Python World!')
wish()
Function Declaration &Calling
Syntax:
def function_name(parameters):
# body
return value
Example:
def add(a, b):
return a + b
result = add(10, 20)
print('Sum =', result)
5.
Parameters vs Arguments
- Parameter: Variable in the function definition.
- Argument: Actual value supplied to a function.
Example:
def square(num):
return num ** 2
print(square(5))
Variable-Length Parameters
Using*args:
def total(*numbers):
print(sum(numbers))
total(10, 20, 30)
Using **kwargs:
def show_info(**data):
for key, value in data.items():
print(key, ':', value)
show_info(name='Ravi', age=19)
10.
Returning Values
defmultiply(a, b):
return a * b
result = multiply(4, 5)
print('Product =', result)
Return keyword sends data back to the caller.
Combined Example Programs
Even or Odd:
def check(num):
return 'Even' if num % 2 == 0 else 'Odd'
print(check(7))
Sum using *args:
def total_sum(*nums):
return sum(nums)
print(total_sum(1, 2, 3))
13.
Best Practices
-Avoid mutable default arguments.
- Use docstrings for documentation.
- Keep functions short and focused.
- Use type hints:
def add(a: int, b: int) -> int:
return a + b
- Prefer keyword arguments for clarity.
14.
Summary
Type |Example | Description
Positional | func(a, b) | Pass values in order
Keyword | func(b=2, a=1) | Use names
Default | def func(a=5) | Uses default
Variable-length | def func(*args) | Multiple values
Keyword variable-length | def func(**kwargs) | Multiple key-value pairs
15.
References
- GeeksforGeeks:Python Functions & Parameters
- Python.org Official Documentation
- Tutorialspoint: Function Arguments in Python