Functions in Python

πΉ 1. What is a Function in Python?
A function is a reusable block of code that performs a specific task.
Instead of writing the same code again and again, you define once, use many times.
Why functions?
Reduce code repetition
Improve readability
Make code modular & testable
Easier debugging
πΉ 2. Basic Function (No Parameters)
Syntax
def function_name():
statements
Example
def greet():
print("Hello, World!")
greet()
π Output:
Hello, World!
π Task 1
Create a function welcome() that prints:
Welcome to Python Programming
πΉ 3. Function with Parameters (Arguments)
Parameters allow us to pass data into a function.
Example
def greet(name):
print("Hello", name)
greet("Aarav")
greet("Python")
π Output:
Hello Aarav
Hello Python
π Task 2
Write a function square(n) that prints the square of a number.
πΉ 4. Function with Return Value
Instead of printing, functions can return values.
Example
def add(a, b):
return a + b
result = add(5, 3)
print(result)
π Output:
8
π return sends data back to the caller.
π Task 3
Create a function is_even(n) that returns True if number is even, else False.
πΉ 5. Types of Arguments in Python
Python supports multiple ways to pass arguments:
β 5.1 Positional Arguments
Order matters.
def student(name, age):
print(name, age)
student("Ram", 20)
β Wrong order:
student(20, "Ram") # logical error
π Task 4
Create a function multiply(a, b, c) and call it using positional arguments.
β 5.2 Keyword Arguments
You specify parameter names β order doesnβt matter.
def student(name, age):
print(name, age)
student(age=21, name="Sita")
π Task 5
Call multiply() using keyword arguments.
β 5.3 Default Arguments
Provide default values.
def greet(name="User"):
print("Hello", name)
greet()
greet("Aarav")
π Task 6
Create a function power(base, exp=2) that returns base raised to power.
πΉ 6. *args (Variable Length Arguments)
Sometimes you donβt know how many arguments will be passed.
π *args stores values as a tuple.
Example
def total(*args):
print(args)
print(sum(args))
total(1, 2, 3)
total(5, 10, 15, 20)
π Output:
(1, 2, 3)
6
(5, 10, 15, 20)
50
Key Points
argsis just a name (convention)*is importantAccess like a tuple
π Task 7
Write a function average(*numbers) that returns the average.
πΉ 7. **kwargs (Keyword Variable Length Arguments)
Used when passing named arguments dynamically.
π **kwargs stores data as a dictionary.
Example
def student_details(**kwargs):
print(kwargs)
student_details(name="Aarav", age=21, course="CS")
π Output:
{'name': 'Aarav', 'age': 21, 'course': 'CS'}
Accessing values
def student_details(**kwargs):
for key, value in kwargs.items():
print(key, ":", value)
π Task 8
Create a function profile(**info) that prints all key-value pairs.
πΉ 8. Combining Arguments (Advanced)
Correct Order
1. Positional
2. *args
3. Default
4. **kwargs
Example
def demo(a, b, *args, x=10, **kwargs):
print(a, b)
print(args)
print(x)
print(kwargs)
demo(1, 2, 3, 4, x=50, name="Ram", age=20)
π Task 9
Create a function bill(customer, *items, discount=0, **details)
Print customer, items, discount, and details.
πΉ 9. Functions as Objects (Advanced Concept)
Functions can be:
Stored in variables
Passed as arguments
Returned from functions
Example
def add(a, b):
return a + b
operation = add
print(operation(3, 4))
π Task 10
Write a function apply(func, a, b) that applies any function to two numbers.
πΉ 10. Lambda Functions (Short Functions)
One-line anonymous functions.
square = lambda x: x * x
print(square(5))
With args
add = lambda *args: sum(args)
print(add(1, 2, 3))
π Task 11
Create a lambda to check if a number is divisible by 5.
πΉ 11. Real-World Example (Mini Project)
Student Marks Calculator
def calculate_marks(name, *marks, **extra):
total = sum(marks)
avg = total / len(marks)
print("Name:", name)
print("Total:", total)
print("Average:", avg)
if "grade" in extra:
print("Grade:", extra["grade"])
calculate_marks(
"Aarav",
80, 75, 90,
grade="A",
remark="Excellent"
)
β Final Practice Assignment (Exam-Level)
Write a function using default arguments
Write a function using *only args
Write a function using **only kwargs
Combine all argument types in one function
Explain difference between
printandreturnWrite a real-life example of
*argsand**kwargs
