←

Python Functions Complete Notes

Master functions in Python with concept breakdowns, line-by-line code explanations in Easy English and Hinglish, and real-world projects.

Author: By Instructor

1. What is a Function & Why Use It?

A function is a reusable block of code designed to perform a specific task. Instead of writing the same code multiple times, you group it inside a function and call it whenever needed.

Easy English Explanation

  • Reusability: Write code once, use it multiple times.
  • Avoid Repetition: Eliminates duplicate code in your project.
  • Readability: Makes code cleaner and easier to understand.
  • Maintainability: Easy to fix bugs in one central location.
  • Modularity: Divides large programs into small manageable modules.

Hinglish Explanation

  • Function ka Matlab: Code ka ek aisa block jise hum ek baar bana kar baar-baar use kar sakte hain.
  • Kyu Use Kare: Agar hume 10 baar same kaam karna hai, to 10 baar code likhne ke bajaye ek function bana kar use call karte hain.
  • Fayde: Time bachta hai, code neat rehta hai aur debugging easy ho jaati hai.

2. Basic Function Syntax & Simple Example

Python Code - Basic Function
def namste():
    print("Hello Gagan")

namste()
Output
Hello Gagan

Line-by-Line Code Breakdown

Line Code Snippet Easy English Explanation Hinglish Explanation
1 def namste(): Defines a function named namste using keyword def. Parentheses () are for parameters, and colon : starts the function body. def keyword se namste naam ka function create kar rahe hain. Colon : batata hai ki block start ho gaya hai.
2 print("Hello Gagan") Indented code block inside the function that prints text to the screen when executed. Function ke andar indented line. Jab function chalega to screen par "Hello Gagan" print hoga.
4 namste() Function Call: Executes the code inside the function namste. Function Call: Function ko execute karne ke liye uska naam () ke saath likhte hain.

3. Parameters vs Arguments

Parameter: A variable declared in the function definition to accept input values.

Argument: The actual value passed to the function when calling it.

Python Code - Parameters and Arguments
def greet(name):
    print(f"Hello {name}")

greet("Gagan")
greet("Rajat")
Output
Hello Gagan
Hello Rajat

Line-by-Line Code Breakdown

Line Code Snippet Easy English Explanation Hinglish Explanation
1 def greet(name): Function header with a parameter named name. It acts as a placeholder for incoming data. Function definition me name variable ek Parameter hai jo value receive karega.
2 print(f"Hello {name}") Uses formatted string (f-string) to embed the value of name into the printed message. f-string ka use karke variable name ki value message me insert kar ke print kar raha hai.
4 greet("Gagan") Calls greet with the string argument "Gagan". Function call ke time pass ki gayi actual value "Gagan" ek Argument hai.
5 greet("Rajat") Calls greet with another argument "Rajat". Doosri call me "Rajat" argument pass ho raha hai.

4. Multiple Parameters & All-in-One Calculator Function

Python Code - Calculator Function
def calculator(a, b):
    print(f"Addition = {a + b}")
    print(f"Subtraction = {a - b}")
    print(f"Multiplication = {a * b}")
    print(f"Division = {a / b}")
    print(f"Floor Division = {a // b}")
    print(f"Modulus = {a % b}")

calculator(17, 4)
Output
Addition = 21
Subtraction = 13
Multiplication = 68
Division = 4.25
Floor Division = 4
Modulus = 1

Line-by-Line Code Breakdown

Line Code Snippet Easy English Explanation Hinglish Explanation
1 def calculator(a, b): Defines a function taking two parameters a and b. Do parameters a aur b lene wala calculator function define kiya.
2-7 print(...) Performs arithmetic operations (+, -, *, /, //, %) and prints results directly. Saare arithmetic operations perform kar ke results screen par print karta hai.
9 calculator(17, 4) Calls function passing 17 for a and 4 for b. 17 aur 4 arguments pass kar ke calculator function call kiya.

5. Print vs Return Statement (Very Important)

print()

Only displays output on the screen. It returns None and cannot be used in further calculations or stored for later logic.

return

Value ko function se bahar bhejta hai taaki usko variable me store kiya ja sake ya aage calculation me use kiya ja sake.

Python Code - Return Statement & Multiple Returns
def add(a, b):
    return a + b

result = add(10, 20)
print(result * 2)

def calculate(a, b):
    addition = a + b
    subtraction = a - b
    multiplication = a * b
    return addition, subtraction, multiplication

res = calculate(20, 5)
print(res)
Output
60
(25, 15, 100)

Line-by-Line Code Breakdown

Line Code Snippet Easy English Explanation Hinglish Explanation
2 return a + b Sends the sum of a and b back to the caller site. Sum ki value ko caller side par return kar raha hai.
4 result = add(10, 20) Stores returned value (30) in variable result. Function se aayi return value (30) ko result variable me save kiya.
5 print(result * 2) Uses stored result in further math (30 * 2 = 60). Saved result ko supercharge karke agle formula me use kiya.
11 return addition, subtraction, multiplication Returns multiple values as a Tuple (25, 15, 100). Multiple values ko ek saath Tuple ke roop me return kar raha hai.

6. Types of Arguments

  • Default Parameter: Value used if no argument is passed during function call.
  • Positional Arguments: Arguments matched in exact order of parameters.
  • Keyword Arguments: Arguments matched explicitly by parameter names (order does not matter).
Python Code - Default & Keyword Arguments
def greet(name="Gagan"):
    print(f"Hello {name}")

greet("Aman")
greet()

def student(name, age):
    print(f"Name = {name}, Age = {age}")

student(age=22, name="Gagan")
Output
Hello Aman
Hello Gagan
Name = Gagan, Age = 22

Line-by-Line Code Breakdown

Line Code Snippet Easy English Explanation Hinglish Explanation
1 def greet(name="Gagan"): Sets default parameter name="Gagan". Default value set ki agar koi argument na paas kare to "Gagan" use ho.
5 greet() Called without argument, so default value "Gagan" is used. Bina argument call kiya, to default value "Gagan" chalegi.
10 student(age=22, name="Gagan") Keyword argument call: assigns 22 to age and "Gagan" to name regardless of position. Keyword arguments: Naam ke saath value di, isliye position change karne se koi farak nahi padta.

7. Arbitrary Arguments: *args and **kwargs

*args (Arbitrary Positional Arguments)

Receives variable number of positional arguments as a Tuple.

**kwargs (Arbitrary Keyword Arguments)

Receives variable number of keyword arguments as a Dictionary.

Python Code - *args and **kwargs
def add_numbers(*numbers):
    total = 0
    for number in numbers:
        total = total + number
    return total

print(add_numbers(10, 20, 30))

def student_info(**details):
    print(details)

student_info(name="Gagan", age=22, city="Chandigarh")
Output
60
{'name': 'Gagan', 'age': 22, 'city': 'Chandigarh'}

Line-by-Line Code Breakdown

Line Code Snippet Easy English Explanation Hinglish Explanation
1 def add_numbers(*numbers): *numbers captures all incoming positional arguments into a single tuple. *numbers jitne bhi numbers bhejoge unko ek tuple banakar le leta hai.
3-4 for number in numbers: Iterates over each number in tuple and calculates cumulative sum. Tuple ke har ek number par loop chala kar unka sum calculate karta hai.
9 def student_info(**details): **details captures key=value pairs into a single dictionary. **details keyword arguments ko key-value pairs wali dictionary bana kar accept karta hai.

8. Functions with Data Structures (Lists & Dictionaries)

Python Code - List & Dictionary in Functions
def print_names(names):
    for name in names:
        print(name)

students = ["Gagan", "Rajat", "Lokesh"]
print_names(students)

def show_student(student):
    print(f"Name = {student['name']}")
    print(f"Age = {student['age']}")

st_dict = {"name": "Gagan", "age": 22}
show_student(st_dict)
Output
Gagan
Rajat
Lokesh
Name = Gagan
Age = 22

Line-by-Line Code Breakdown

Line Code Snippet Easy English Explanation Hinglish Explanation
1-3 def print_names(names): Receives a list as parameter and iterates through it using a for loop. List ko parameter me receive karta hai aur for loop se saare names print karta hai.
8-10 def show_student(student): Receives a dictionary and accesses its values using key names like student['name']. Dictionary pass hone par uske keys (name, age) ko read karke formatted text dikhata hai.

9. Logic Building & Mathematical Functions

Python Code - Even/Odd, Max, Geometry
def check_even_odd(number):
    if number % 2 == 0:
        return "Even"
    else:
        return "Odd"

def largest(a, b, c):
    if a >= b and a >= c:
        return a
    elif b >= a and b >= c:
        return b
    else:
        return c

def circle_area(radius):
    return 3.14 * radius * radius

print(check_even_odd(10))
print(largest(10, 50, 15))
print(circle_area(5))
Output
Even
50
78.5

Line-by-Line Code Breakdown

Line Code Snippet Easy English Explanation Hinglish Explanation
2 if number % 2 == 0: Checks if number divided by 2 leaves remainder zero (Even condition). Remainder 0 hai ya nahi check karta hai (Even/Odd test).
7-12 if a >= b and a >= c: Uses logical AND to determine maximum among three numbers. 3 numbers me se maximum nikalne ke liye logical conditions check karta hai.
15 return 3.14 * radius * radius Calculates circle area using formula pi * r^2 and returns float. Circle ke area ka formula pi * r square lagakar result return karta hai.

10. Lambda, Map & Filter Functions

Lambda Function: A small anonymous function written in a single line. Syntax: lambda arguments: expression

map(): Applies a function to every item in an iterable.

filter(): Filters elements from an iterable based on a boolean condition function.

Python Code - Lambda, Map, Filter
square = lambda x: x * x
print(square(5))

numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)

evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Output
25
[2, 4, 6, 8, 10]
[2, 4]

Line-by-Line Code Breakdown

Line Code Snippet Easy English Explanation Hinglish Explanation
1 square = lambda x: x * x Creates a one-line anonymous function that squares its argument x. Lambda se ek single line function banaya jo input x ka square nikalta hai.
5 map(lambda x: x * 2, numbers) Applies the lambda (multiply by 2) to each number in the list. List ke har element ko 2 se multiply karne ke liye map function lagaya.
8 filter(lambda x: x % 2 == 0, numbers) Keeps only elements where the lambda evaluates to True (Even numbers). Wahi elements filter karta hai jo condition (even) ko satisfy karte hain.

11. Variable Scope & Global Keyword

Python Code - Scope and global keyword
count = 0

def increase():
    global count
    count = count + 1

increase()
increase()
print(count)
Output
2

Line-by-Line Code Breakdown

Line Code Snippet Easy English Explanation Hinglish Explanation
1 count = 0 Global variable declared outside function. Function ke bahar banaya gaya Global Variable.
4 global count Declares inside function that count refers to the global variable. global keyword batata hai ki hum bahar wale count ko update karna chahte hain.
5 count = count + 1 Modifies the global counter variable. Global count me 1 increment karta hai.

12. 25 Practice Questions with Full Solutions

Practice Questions 1 - 25 Code Solutions
def q1():
    print("Hello World")

def q2(name):
    print(f"Hello {name}")

def q3(a, b):
    return a + b

def q4(a, b):
    return a - b

def q5(a, b):
    return a * b

def q6(a, b):
    return a / b if b != 0 else "Error"

def q7(n):
    return "Even" if n % 2 == 0 else "Odd"

def q8(n):
    if n > 0: return "Positive"
    elif n < 0: return "Negative"
    else: return "Zero"

def q9(a, b, c):
    return max(a, b, c)

def q10(l, w):
    return l * w

def q11(r):
    return 3.14 * r * r

def q12(b, h):
    return 0.5 * b * h

def q13(a, b):
    return (a + b) / 2

def q14(numbers):
    total = 0
    for num in numbers:
        total += num
    return total

def q15(numbers):
    return sum(1 for x in numbers if x % 2 == 0)

def q16(text):
    return text[::-1]

def q17(text):
    return text == text[::-1]

import re
def q18(email):
    pattern = r"^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}"
    return "Valid Email" if re.fullmatch(pattern, email) else "Invalid Email"

def q19(phone):
    return "Valid Phone" if re.fullmatch(r"^\d{10}$", phone) else "Invalid Phone"

def q20(marks):
    if marks >= 90: return "A+"
    elif marks >= 80: return "A"
    elif marks >= 70: return "B"
    elif marks >= 60: return "C"
    elif marks >= 40: return "D"
    else: return "Fail"

def q21(age):
    return "Eligible" if age >= 18 else "Not Eligible"

def q22(price, discount):
    return price - (price * discount / 100)

def q23(p, r, t):
    return (p * r * t) / 100

def q24(*args):
    return sum(args)

def q25(**kwargs):
    for key, val in kwargs.items():
        print(f"{key}: {val}")

13. Real-World Applications & Mini Projects

Mini Project 1: Calculator using Functions

Python Code - Calculator Project
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b): return a / b if b != 0 else "Cannot divide by zero"

num1 = 20.0
num2 = 5.0

print(f"Addition = {add(num1, num2)}")
print(f"Subtraction = {subtract(num1, num2)}")
print(f"Multiplication = {multiply(num1, num2)}")
print(f"Division = {divide(num1, num2)}")
Output
Addition = 25.0
Subtraction = 15.0
Multiplication = 100.0
Division = 4.0

Mini Project 2: Shopping Bill with Discount

Python Code - Shopping Bill
def calculate_total(price, quantity):
    return price * quantity

def calculate_discount(total, discount_percent):
    return total - (total * discount_percent / 100)

price = 500.0
quantity = 3
discount = 10.0

total = calculate_total(price, quantity)
final_amount = calculate_discount(total, discount)

print(f"Total Bill = {total}")
print(f"Final Amount after Discount = {final_amount}")
Output
Total Bill = 1500.0
Final Amount after Discount = 1350.0