Lesson 6: Functions & Modules in Python

Functions & Modules in Python – Code Ka Real Magic 🧠⚡

Bro, sach bataun? Jab main pehli baar Python seekh raha tha na, mujhe laga “functions” bas ek boring topic hoga — kuch formula type cheez. Lekin bhai, ye toh pura game changer nikla 😎. Ye woh power hai jisse tu apna code chhote-chhote pieces me tod sakta hai, reusable bana sakta hai, aur pro coder jaisa feel aata hai.

So today, hum seekhenge — Functions, Arguments, Return Values, Default Parameters, *args, **kwargs, Lambda, Scope, aur Modules. Haan, sab kuch ek hi jagah. Ready? Chal shuru karte hain bro style me 🔥☕


Functions – Code ka Reusable Jadoo ✨

Soch, tu ek cafe me kaam karta hai aur har baar manually coffee bana raha hai. Bore nahi ho gaya? 😅 Ab agar tu ek machine bana de jo “ek baar setup ho, aur baar baar kaam kare”? Wahi hota hai function!

def make_coffee():
    print("Coffee ready bro ☕")

Yahan def se humne ek function define kiya. Ab ise kabhi bhi bula lo:

make_coffee()

Output: Coffee ready bro ☕

Bas itna hi funda hai — define karo aur call karo. Har baar copy-paste karne se behtar, ek baar likh aur reuse karte raho 😎


Arguments & Return Values – Function ke Ingredients 🍲

Bro, bina ingredients ke coffee nahi banti, waise hi bina arguments ke function ka kya fayda? Let’s see:

def make_coffee(type, sugar):
    print(f"{type} coffee with {sugar} sugar cubes ready! ☕")
make_coffee("Cold", 2)

Output: Cold coffee with 2 sugar cubes ready! ☕

Yahan type aur sugar function ke parameters hain, aur jo hum pass karte hain wo arguments.

Return Value – Function ka Result 🎁

Bro, kabhi tu chaahe ke function bas print na kare, balki kuch wapas de jise tu use kar sake? Dekh:

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

result = add(10, 5)
print("Sum:", result)

Output: Sum: 15

return keyword function se value bahar bhejta hai. Soch, ye tere function ka “output box” hai 🎁.


Default Arguments – Jab Kuch Na Ho, Toh Ye Lo 😅

Default argument basically backup plan hota hai. Agar tu koi value na de, toh Python automatically default value le lega.

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

greet("Ritik")
greet()

Output:

Hello, Ritik! 👋
Hello, Bro! 👋

Dekha? Second call me name nahi diya, toh “Bro” default le liya. Bilkul jaise mom kehti hai, “khana nahi banaya? Parle-G kha le beta.” 😂


*args & **kwargs – Jab Data Control Se Bahar Ho 😆

*args – Multiple Positional Arguments

Kabhi kabhi tu nahi jaanta kitne arguments milne wale hain. Tab aata hai *args — sabko ek tuple me store kar leta hai.

def add_numbers(*args):
    total = sum(args)
    print("Total sum:", total)

add_numbers(2, 3)
add_numbers(1, 2, 3, 4, 5)

Output:

Total sum: 5
Total sum: 15

**kwargs – Keyword Arguments

Ye tab use hota hai jab tu key-value pairs bhejna chahe.

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

show_info(name="Ritik", age=21, hobby="Coding")

Output:

name: Ritik
age: 21
hobby: Coding

Ek dum flexible concept hai bro — function ko superhero bana deta hai 🦸‍♂️


Lambda Functions – Shortcuts for Smart Coders ⚡

Bro, kabhi kabhi tu bas ek line ka function banana chahta hai. Tab pura “def” likhna feels like overkill. Enter: lambda.

square = lambda x: x * x
print(square(6))

Output: 36

One-liner functions ke liye lambda best hai. Example, sorting me:

nums = [3, 1, 4, 2]
nums.sort(key=lambda x: x)
print(nums)

Bas ek line aur kaam done 😎


Scope – Local vs Global Battle Royale ⚔️

Bro, ye concept thoda tricky hai. Scope matlab variable kahaan tak visible hai. Dekh example:

x = 10  # global

def show():
    x = 5  # local
    print("Inside:", x)

show()
print("Outside:", x)

Output:

Inside: 5
Outside: 10

Rule simple hai — function ke andar bana variable sirf uske andar kaam karega. Agar tu global variable ko modify karna chahe, toh likh:

x = 10

def change():
    global x
    x = 20

change()
print(x)

Output: 20

Bas dhyan rahe, global variable zyada modify mat karna — bug aaye toh pakadna mushkil ho jaata hai 😅


Modules & Packages – Code Reuse ka Asli Tadka 🍱

Soch bro, tu ek game bana raha hai aur har file me same function likhna pad raha hai. Thoda repetitive lag raha hai na? Wahi time pe tu bana sakta hai apna module.

# mymodule.py
def greet(name):
    print(f"Yo {name}! Welcome back 🔥")

Ab doosre file me:

import mymodule
mymodule.greet("Ritik")

Output: Yo Ritik! Welcome back 🔥

Ab samajh gaya? Module ek Python file hoti hai jisme functions likhe hote hain. Import karo aur chill karo 😎

Packages – Folder Wale Modules

Jab tere paas multiple modules ho, tu unhe ek folder me rakhta hai with __init__.py file. That becomes a package. Jaise:

  • game_utils/graphics.py
  • game_utils/sound.py

Bas fir import kar: from game_utils import graphics

Packages se bada project ekdum manageable ban jaata hai 💪


Python Standard Library – Ready-Made Tools 🧰

Bro, Python already tere liye full toolbox leke aata hai — use kar aur king ban ja!

  • os – folders/files handle karne ke liye
  • sys – system-level info jaise Python version
  • math – mathematical functions
  • random – random numbers (game banate time must use)
  • datetime – date & time ke liye

Example:

import os, sys, math, random, datetime

print("Current dir:", os.getcwd())
print("Python version:", sys.version)
print("Square root of 16:", math.sqrt(16))
print("Random number:", random.randint(1, 10))
print("Current time:", datetime.datetime.now())

Bro, seriously — ye library ek goldmine hai. Half code likhne ki zarurat hi nahi padti 😎


Mini Project Time 🎮 – Rock, Paper, Scissors Game

Ab theory se thoda hatke karte hain masti! Banate hain ek simple game jahan computer aur tu face off karega 😆

import random

def play():
    print("Welcome to Rock-Paper-Scissors 🎮")
    user = input("Choose rock, paper, or scissors: ").lower()
    computer = random.choice(["rock", "paper", "scissors"])

    print(f"Computer chose: {computer}")

    if user == computer:
        return "It's a tie bro!"
    elif is_win(user, computer):
        return "You win! 🔥"
    else:
        return "You lose 😢"

def is_win(player, opponent):
    return (player == "rock" and opponent == "scissors") or \
           (player == "scissors" and opponent == "paper") or \
           (player == "paper" and opponent == "rock")

print(play())

Dekha? Chhota code, but pura functional — random module, functions, return value, sab ek saath 💪


Common Mistakes Juniors Karte Hain 😬

  • Return likhna bhool jaana (fir None dekh ke panic karna 😂)
  • Global aur local variables mix kar dena
  • Function ke andar variable use karna bina define kiye
  • Lambda har jagah use karna — readability mar jaati hai bro
  • Apne module ka naam “math.py” rakh dena (Python confuse ho jaata hai 😅)

Bro-to-Bro Gyaan 💬

Bro, ab tu Python ke ek solid stage pe aa gaya hai. Functions aur modules ke bina koi bada project possible nahi. Ye tujhe allow karte hain code ko clean, readable, aur reuse-friendly banane me.

Main bhi pehle har jagah same code likh ke bore hota tha. Par jab maine functions samjhe na — life sorted! Tu bhi thoda practice kar, har feature ko function me tod de, aur fir dekhiye — tera code ekdum “professional” lagne lagega 👨‍💻✨


Next Steps 🚀

  • Ek “Calculator App” bana using functions.
  • Ek “Math Utility Module” bana jisme sab add, sub, multiply, divide functions likh.
  • Try importing your own module in another script.

Next blog me hum karenge File Handling in Python — jahan tu data ko read-write karega jaise hacker 😎💾

Tab tak code likh, errors maar, aur Python se dosti bana. Yaad rakh — Code likhoge tabhi sikhenge 💻❤️

Post a Comment

0 Comments