Python Functions - Detailed Guide with Examples

1. Functions kya hote hain?

Function ek reusable code block hai jo ek specific kaam karta hai. Jab bhi hume wo kaam karna hota hai, hum function ko call karte hain jisse baar-baar code likhne ki zarurat nahi padti.

Faayde:

2. Function ka basic syntax

Function define karne ke liye Python me def keyword lagate hain, uske baad function naam aur parentheses me parameters (agar hain) likhte hain. Function ka body indentation me hota hai.

def function_name(parameters):
    """Optional docstring explaining the function"""
    # function ka main code yahan likhte hain
    return value  # optional
  

3. Simple function example

Neeche ek simple function hai jo sirf console pe message print karta hai.

def greet():
    print("Hello, World!")

greet()  # Function call; output: Hello, World!
  

4. Function me parameters aur arguments

Parameters function define karte waqt likhe jaate hain. Arguments wo actual values hain jo function call karte waqt diye jaate hain.

def greet(name):
    print(f"Hello, {name}!")

greet("Amit")  # Output: Hello, Amit!
greet("Sita")  # Output: Hello, Sita!
  

5. Return statement kaise kaam karta hai

Return statement function ka result bahar bhejta hai jise hum variable me store karke baad me use kar sakte hain.

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

result = add(10, 7)
print("Sum is:", result)  # Output: Sum is: 17
  

6. Default parameters

Agar function call karte waqt argument na diya jaye to default value use hoti hai:

def greet(name="Guest"):
    print(f"Hello, {name}!")

greet()        # Output: Hello, Guest!
greet("Ravi")  # Output: Hello, Ravi!
  

7. Variable-length arguments: *args aur **kwargs

*args use hota hai jab hume unknown number of positional arguments leney ho, aur **kwargs use hota hai unknown number of keyword arguments lene ke liye.

def add_all(*args):
    total = 0
    for num in args:
        total += num
    return total

print(add_all(1, 2, 3))        # Output: 6
print(add_all(4, 5, 6, 7, 8)) # Output: 30

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

show_info(name="Amit", age=25, city="Delhi")
  

8. Recursive function ka example

Recursive function apne aap ko call karta hai. Factorial function iska famous example hai:

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))  # Output: 120 (5 * 4 * 3 * 2 * 1)
  

9. Lambda function (Anonymous function)

Chhote simple functions ke liye hum lambda function use kar sakte hain jo ek line me likh jaata hai:

square = lambda x: x * x
print(square(6))  # Output: 36
  

10. Local aur Global variables ka farak

Jo variable function ke andar declare hota hai use local variable kehte hain. Wo function ke bahar accessible nahi hota. Jo variable function ke bahar declare ho wo global variable kehlata hai aur functions me accessible hota hai.

x = 10  # Global variable

def test():
    y = 5  # Local variable
    print("Inside function:", x, y)

test()                # Output: Inside function: 10 5
print("Outside function:", x)  # Output: Outside function: 10
# print(y)  # Error: y is not defined outside the function
  

11. Function Docstring

Function ke starting me triple quotes ke andar likha gaya text docstring kehlata hai. Ye function ki purpose explain karta hai aur documentation me dikhta hai.

def greet(name):
    """Ye function user ko greet karta hai."""
    print(f"Hello, {name}!")

print(greet.__doc__)  # Output: Ye function user ko greet karta hai.
  

12. Practical example: Rectangle area calculate karna

Ek function banate hain jo rectangle ka area calculate karega:

def calculate_area(length, width):
    """Rectangle ka area calculate karta hai."""
    return length * width

l = 10
w = 5
area = calculate_area(l, w)
print("Length:", l)
print("Width:", w)
print("Area:", area)  # Output: Area: 50