<DataInsights />
  • 🏠 Home
  • πŸ“Š SQL
  • 🐍 Python
  • πŸ“ˆ Power BI
  • πŸ“— Excel
  • πŸ’Ό Career
  • 🎯 Interview Q&A
  • πŸ“ Case Study
  • πŸ“₯ Downloads
  • πŸš€ My Portfolio
<DataInsights />

Practical Data Analytics tutorials covering SQL, Python, Power BI, Excel and career guidance for aspiring analysts β€” 100% free.

Topics

  • SQL Tutorials
  • Python Guide
  • Power BI
  • Excel Tips
  • Career Guide

Quick Links

  • πŸ› οΈ All Tools
  • πŸ—“οΈ Archive
  • πŸ“¬ Contact
  • πŸ” Search
  • Portfolio
  • Kaggle
  • GitHub

Legal & Info

  • About
  • Contact
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • DMCA
  • Sitemap
Copyright © 2026 Data Insights by Jatin Kumar. All Rights Reserved.Built with ❀️ for Data Analysts
Home/Python/Functions & Lambda β€” Complete Deep Dive...

Functions & Lambda β€” Complete Deep Dive

A
August 6, 2026 Jatin Kumar 38 min read Python
Data Insights Python Handbook β€” Part 8

Functions & Lambda β€” Complete Deep Dive πŸ”§

Functions Python ka backbone hain β€” code reusability, modularity, aur clean architecture ki foundation. Basic def se lekar *args, **kwargs, Lambda, Decorators, aur Type Hints tak β€” complete deep dive. Data Insights par.

πŸ“‘ Is Chapter Mein Kya Sikhenge:

  • 🟒 Basic: Functions Intro, Parameters vs Arguments, Default Parameters
  • 🟑 Medium: Keyword Arguments, *args, **kwargs
  • πŸ”΄ Advanced (Part 8B): Return Multiple Values, Scope (LEGB), Lambda, map/filter/reduce, Decorators, Type Hints

1. Functions Introduction β€” def, call, return 🟒

πŸ“˜ Definition: A Function is a reusable block of code that performs a specific task. It is defined using the def keyword, followed by the function name, parameters in parentheses, and a colon. The function body is indented. Functions may or may not return a value. Functions promote code reusability, modularity, and readability β€” write once, use many times.

🎯 Samjho Hinglish Mein: Function ek recipe hai. Ek baar likh diya (define), phir baar baar use karo (call). "Cha banao" ek function hai β€” ek baar recipe likhi, jab bhi cha chahiye, "cha_banao()" call kar do. Bina function ke same code baar baar copy-paste karna padta hai β€” DRY principle violate hoti hai (Don't Repeat Yourself). Functions se code clean, maintainable, aur reusable banta hai.

πŸ“‹ Function Syntax & Rules:

Syntax: def function_name(parameters): """Docstring (optional)""" # Function body return value # Optional
Rules:
β€’ Function name should be lowercase, use underscores (snake_case)
β€’ Cannot start with number
β€’ Cannot use Python keywords (if, for, def, class, etc.)
β€’ Body must be indented (4 spaces recommended)
β€’ return statement is OPTIONAL β€” default return is None
β€’ Function name should describe what it does

πŸ’» Examples:

# Example 1: Simple function without parameters def greet(): print("Hello, welcome to Python!")
# Call the function
greet() # Hello, welcome to Python!
greet() # Hello, welcome to Python! (call again β€” reusable!)
greet() # Hello, welcome to Python!
# Example 2: Function with parameters & return def add_numbers(a, b): result = a + b return result # Call and capture returned value total = add_numbers(10, 20) print(total) # 30 # Use return value directly print(add_numbers(5, 15)) # 20 print(add_numbers(100, 200)) # 300
# Example 3: Practical β€” Calculate discount def calculate_discount(price, discount_percent): """Calculate final price after discount""" discount_amount = price * discount_percent / 100 final_price = price - discount_amount return final_price # Use for multiple products print(calculate_discount(1000, 10)) # 900.0 print(calculate_discount(5000, 20)) # 4000.0 print(calculate_discount(2500, 15)) # 2125.0 # Same function, different inputs β€” reusability!
⚠️ Common Mistake: Function def se define karna aur function CALL karna alag hain! def greet(): sirf function BANATA hai β€” execute nahi karta. Function tab execute hota hai jab tum greet() call karte ho (parentheses ke saath). Bina call kiye function chalta hi nahi!

πŸ’¬ Interview Q&A:

Q: Function kyun use karte hain?
Ans: Teen main reasons: (1) Reusability β€” same code baar baar likhne se bachte hain, ek function likho, kahin bhi call karo. (2) Modularity β€” bada program chhote functions mein todhte hain, easier to debug and maintain. (3) Readability β€” well-named function code ko self-documenting banata hai β€” calculate_tax() function ka naam hi purpose bata deta hai. DRY principle (Don't Repeat Yourself) follow hoti hai.

Q: return statement kyun important hai?
Ans: return function ka OUTPUT deta hai β€” jo caller use kar sake. Bina return ke function calculate toh karega lekin result waapas nahi bhejega β€” value gum ho jaayegi. print() sirf display karta hai, return calculation waapas de deta hai β€” us value ko variable mein store kar sakte ho, doosre calculations mein use kar sakte ho. Rule: Calculation function β†’ return use karo. Display function β†’ print use karo.

2. Parameters vs Arguments 🟒

πŸ“˜ Definition: Parameters are the variables listed in the function definition (parentheses after function name). Arguments are the actual VALUES passed to the function when calling it. Parameters are placeholders, arguments are real data. This distinction is important in interviews and understanding Python.

🎯 Samjho Hinglish Mein: Function likhte waqt jo variables likhte ho β€” woh Parameters hain (placeholders). Function call karte waqt jo values pass karte ho β€” woh Arguments hain. Example: def add(a, b) mein a, b PARAMETERS hain. add(10, 20) mein 10, 20 ARGUMENTS hain. Parameters = khaali dabbe, Arguments = un dabbon mein daali gayi cheezein.

πŸ“‹ Comparison:

Feature Parameters Arguments
Where Function definition (def line) Function call
What Variables (placeholders) Actual values passed
Example def add(a, b): add(10, 20)
Purpose Define what function needs Provide actual data

πŸ’» Examples:

# Example 1: Positional Arguments (order matters!) def introduce(name, age, city): # name, age, city β†’ Parameters print(f"Hi, I'm {name}, {age} years old, from {city}")
# Arguments passed in order:
introduce("Jatin", 25, "Gurugram")
# Hi, I'm Jatin, 25 years old, from Gurugram

# ⚠️ ORDER MATTERS in positional args!
introduce(25, "Jatin", "Gurugram")
# Hi, I'm 25, Jatin years old, from Gurugram (wrong!)
# Example 2: Wrong number of arguments β€” Error! def add(a, b):
     return a + b # Correct call print(add(10, 20)) # 30 βœ… # Too few arguments # add(10) β†’ TypeError: missing 1 required positional argument: 'b' # Too many arguments # add(10, 20, 30) β†’ TypeError: takes 2 positional arguments but 3 were given
# Example 3: Passing different data types def process_data(name, scores, is_active):
     print(f"Name: {name}") print(f"Total Scores: {sum(scores)}") print(f"Active: {is_active}") # Pass string, list, boolean process_data("Jatin", [85, 90, 78], True) # Name: Jatin # Total Scores: 253 # Active: True

3. Default Parameters 🟒

πŸ“˜ Definition: Default Parameters allow you to specify a default value for a parameter in the function definition. If the caller doesn't provide that argument, the default value is used. Default parameters make functions more flexible and reduce the need to always pass all arguments. Important Rule: Default parameters MUST come AFTER non-default parameters.

🎯 Samjho Hinglish Mein: Default parameter = "agar tumne kuch nahi diya toh yeh default value use hogi." Restaurant mein bolo "cha" β€” agar tum "adrak wali" ya "elaichi wali" specify nahi karte toh chef default (normal cha) bana dega. Function mein bhi same β€” def greet(name, greeting="Hello") β€” agar greeting nahi diya toh "Hello" use hoga. Flexibility milti hai β€” kabhi override karo, kabhi default rakho.

πŸ’» Examples:

# Example 1: Basic default parameter def greet(name, greeting="Hello"): return f"{greeting}, {name}!"
# Without providing greeting β€” uses default
print(greet("Jatin"))
# Hello, Jatin!

# Provide custom greeting β€” overrides default
print(greet("Priya", "Namaste"))
# Namaste, Priya!

print(greet("Rahul", "Hi"))
# Hi, Rahul!
# Example 2: Multiple defaults def create_user(name, age=18, role="User", is_active=True):
     return { "name": name, "age": age, "role": role, "active": is_active } # Only name required β€” rest defaults print(create_user("Jatin")) # {'name': 'Jatin', 'age': 18, 'role': 'User', 'active': True} # Override some defaults print(create_user("Admin", role="Admin")) # {'name': 'Admin', 'age': 18, 'role': 'Admin', 'active': True} # Override all print(create_user("Test", 25, "Manager", False)) # {'name': 'Test', 'age': 25, 'role': 'Manager', 'active': False}
# Example 3: ⚠️ IMPORTANT RULE β€” order matters! # βœ… CORRECT: defaults AFTER non-defaults def calc(a, b, operation="add"):
     if operation == "add":
     return a + b elif operation == "multiply":
     return a * b print(calc(10, 20)) # 30 (default add) print(calc(10, 20, "multiply")) # 200 # ❌ WRONG: default BEFORE non-default # def bad_func(a=10, b): β†’ SyntaxError! # Non-default argument follows default argument
⚠️ CRITICAL WARNING β€” Mutable Default Arguments: NEVER use mutable objects (list, dict, set) as default parameters! def add_item(item, my_list=[]) β€” yeh list ek hi baar create hoti hai aur SHARE hoti hai across all calls! Har call mein items add hote jaate hain β€” bug! Fix: def add_item(item, my_list=None): if my_list is None: my_list = []. Yeh Python ka famous gotcha hai β€” interviews mein puchha jaata hai!

πŸ’¬ Interview Q&A:

Q: Default parameters ki position kya honi chahiye function definition mein?
Ans: Default parameters HAMESHA non-default parameters ke BAAD aane chahiye. def func(a, b, c=10) βœ… correct. def func(a=10, b, c) ❌ SyntaxError! Reason: Python left-to-right positional arguments assign karta hai β€” agar beech mein default hoga toh ambiguity ho jaayegi ki kaunsa value kaunse parameter ke liye hai. Rule: required args pehle, optional (default) args baad mein.

Q: Mutable default argument problem kya hai?
Ans: Python mein default arguments FUNCTION DEFINITION TIME par evaluate hote hain β€” sirf ek baar! Agar default value mutable hai (list, dict), toh sab calls mein SAME object share hota hai. Example: def add(x, lst=[]): lst.append(x); return lst. Pehli call add(1) β†’ [1]. Doosri call add(2) β†’ [1, 2] (not [2]!). Fix: def add(x, lst=None): if lst is None: lst = []. Yeh Python ka famous gotcha hai β€” interviews mein zaroor puchha jaata hai!

4. Keyword Arguments 🟑

πŸ“˜ Definition: Keyword Arguments (kwargs) allow you to pass arguments to a function using the parameter name explicitly β€” like function(name="Jatin", age=25). This way, the ORDER doesn't matter β€” Python matches argument to parameter by name, not position. Keyword arguments make code more readable and less error-prone.

🎯 Samjho Hinglish Mein: Positional arguments mein order important hai β€” add(10, 20) mein pehla 10 a, doosra 20 b. Keyword arguments mein tum naam batate ho β€” add(a=10, b=20) ya add(b=20, a=10) β€” dono same result! Order matter nahi karta. Yeh readability improve karta hai β€” function call dekhne se hi pata chal jaata hai kaunsa value kaunse parameter ke liye hai.

πŸ’» Examples:

# Example 1: Keyword args β€” order doesn't matter! def introduce(name, age, city): return f"{name}, {age}, from {city}"
# Positional (order matters)
print(introduce("Jatin", 25, "Gurugram"))
# Jatin, 25, from Gurugram

# Keyword args β€” order doesn't matter!
print(introduce(city="Delhi", name="Priya", age=28))
# Priya, 28, from Delhi

print(introduce(age=30, name="Rahul", city="Mumbai"))
# Rahul, 30, from Mumbai
# Example 2: Mix positional + keyword args def book_ticket(name, source, destination, class_type="Economy"):
     return f"{name} β€” {source} to {destination} ({class_type})" # Positional first, then keyword print(book_ticket("Jatin", "Delhi", "Mumbai", class_type="Business")) # Jatin β€” Delhi to Mumbai (Business) # Only override specific default print(book_ticket("Priya", "Chennai", "Bangalore")) # Priya β€” Chennai to Bangalore (Economy) # ⚠️ RULE: Positional args MUST come before keyword args # book_ticket(name="Jatin", "Delhi", "Mumbai") β†’ SyntaxError!
# Example 3: Readability comparison β€” REAL WORLD def send_email(to, subject, body, cc=None, bcc=None, priority="normal"): return f"Email sent to {to} with priority {priority}" # ❌ Bad β€” hard to understand what each argument does send_email("jatin@gmail.com", "Meeting", "Tomorrow 5pm", None, None, "high") # βœ… Good β€” self-documenting with keyword args send_email( to="jatin@gmail.com", subject="Meeting", body="Tomorrow 5pm", priority="high" ) # Much clearer! Skip cc and bcc β€” defaults used
πŸ“‹ Best Practice: Functions mein 3+ parameters hain toh keyword args use karo β€” code much more readable ho jaata hai. Compare: merge_data(df1, df2, "inner", ["id"], True, False) vs merge_data(df1, df2, how="inner", on=["id"], sort=True, indicator=False). Doosra clear hai! Pandas mein bhi hamesha keyword args use hote hain isliye.

πŸ’¬ Interview Q&A:

Q: Positional aur Keyword arguments mein kya difference hai?
Ans: Positional args ORDER par depend karte hain β€” func(a, b) mein pehla arg a, doosra b. Order galat toh values swap ho jaayengi. Keyword args NAAM se pass hote hain β€” func(a=10, b=20) β€” order matter nahi karta. Rules: (1) Positional args pehle likhne padte hain, keyword args baad mein. (2) Keyword args self-documenting hain β€” readability better. (3) Optional/default args ke liye keyword args best hain. Real code mein β€” 2 args positional theek hai, 3+ args keyword args use karo.

5. *args β€” Variable Positional Arguments 🟑

πŸ“˜ Definition: *args allows a function to accept a VARIABLE number of positional arguments. The asterisk * before the parameter name tells Python to pack all extra positional arguments into a TUPLE. The name "args" is convention β€” you can name it anything (*items, *numbers), but stick to *args for readability.

🎯 Samjho Hinglish Mein: Kabhi tumhe pata nahi hota ki function ko kitne arguments chahiye. Jaise sum() function β€” 2 numbers ho ya 100, sab work karta hai. *args se yeh possible hai β€” tum jitne bhi arguments pass karo, Python un sab ko ek TUPLE mein pack kar deta hai. def add(*nums) mein add(1,2,3,4,5) β€” nums = (1,2,3,4,5). Ab tuple par iterate karke sum kar sakte ho.

πŸ’» Examples:

# Example 1: Basic *args β€” accept any number of arguments def add_all(*numbers): print(f"Received: {numbers}") print(f"Type: {type(numbers)}") return sum(numbers)
# Pass any number of args
print(add_all(1, 2, 3))
# Received: (1, 2, 3)
# Type: 
# 6

print(add_all(10, 20, 30, 40, 50))
# Received: (10, 20, 30, 40, 50)
# 150

print(add_all()) # Empty tuple ()
# 0
# Example 2: *args with regular parameters def shopping_bill(customer_name, *items):
     print(f"Customer: {customer_name}") print(f"Items purchased:") for i, item in enumerate(items, 1):
     print(f" {i}. {item}") print(f"Total items: {len(items)}") shopping_bill("Jatin", "Milk", "Bread", "Eggs", "Butter") # Customer: Jatin # Items purchased: # 1. Milk # 2. Bread # 3. Eggs # 4. Butter # Total items: 4
# Example 3: Unpacking a list into *args def max_of_all(*numbers):
     if not numbers:
     return None return max(numbers) # Normal call print(max_of_all(10, 45, 23, 78, 12)) # 78 # Unpack a list using * β€” magic! scores = [85, 92, 78, 96, 88] print(max_of_all(*scores)) # 96 # *scores unpacks list to individual args: 85, 92, 78, 96, 88 # Without unpacking β€” treats list as single argument (wrong!) # print(max_of_all(scores)) β†’ TypeError!
⚠️ Important: *args function DEFINITION mein "pack" karta hai (extra args ko tuple mein), aur function CALL mein "unpack" karta hai (list/tuple ko individual args mein). Definition mein *args, call mein *list β€” dono ka same asterisk lekin ulta kaam! Yeh Python ka powerful feature hai β€” jaise print(*list) se list ke saare items separate arguments ban jaate hain.

πŸ’¬ Interview Q&A:

Q: *args kya hai aur kab use karte hain?
Ans: *args function ko VARIABLE number of positional arguments accept karne ki flexibility deta hai. Sab extra arguments ek TUPLE mein pack ho jaate hain. Use cases: (1) Aggregation functions β€” sum(1,2,3,4,5). (2) Utility functions jahan arg count fixed nahi. (3) Wrappers around other functions. Naam "args" convention hai β€” *numbers, *items bhi valid hai. Asterisk zaroori hai β€” woh Python ko batata hai "pack these into tuple".

Q: def func(*args) aur func(*list) β€” dono asterisk ka kya matlab?
Ans: Dono asterisk hain lekin ulta kaam! DEFINITION mein def func(*args) β€” Python bolta hai "extra args ko args tuple mein PACK karo". CALL mein func(*my_list) β€” Python bolta hai "list ke items ko individual args mein UNPACK karo". Same symbol, opposite operations. Pack (definition side) = jodo. Unpack (call side) = todho.

6. **kwargs β€” Variable Keyword Arguments 🟑

πŸ“˜ Definition: **kwargs allows a function to accept a VARIABLE number of KEYWORD arguments. The double asterisk ** before the parameter name tells Python to pack all extra keyword arguments into a DICTIONARY (key = argument name, value = argument value). Convention: use **kwargs β€” but any name works.

🎯 Samjho Hinglish Mein: *args extra positional arguments ko TUPLE mein pack karta hai. **kwargs extra KEYWORD arguments ko DICTIONARY mein pack karta hai. def func(**kwargs) mein func(name="Jatin", age=25) β€” kwargs = {"name": "Jatin", "age": 25}. Ab dictionary par iterate karke process kar sakte ho. Yeh flexible API design ke liye bahut useful hai β€” Django, Flask, requests library sab **kwargs use karte hain.

πŸ’» Examples:

# Example 1: Basic **kwargs def print_info(**details): print(f"Received: {details}") print(f"Type: {type(details)}") for key, value in details.items(): print(f"{key}: {value}")
print_info(name="Jatin", age=25, city="Gurugram")
# Received: {'name': 'Jatin', 'age': 25, 'city': 'Gurugram'}
# Type: 
# name: Jatin
# age: 25
# city: Gurugram
# Example 2: Combining *args and **kwargs def flexible_func(required_arg, *args, **kwargs):
     print(f"Required: {required_arg}") print(f"Positional (args): {args}") print(f"Keyword (kwargs): {kwargs}") flexible_func( "Hello", # required_arg 1, 2, 3, # *args β†’ (1, 2, 3) name="Jatin", # **kwargs β†’ {'name': 'Jatin', ...} age=25 ) # Required: Hello # Positional (args): (1, 2, 3) # Keyword (kwargs): {'name': 'Jatin', 'age': 25}
# Example 3: Real-world β€” API config function def create_user_profile(name, **profile_data): profile = {"name": name} profile.update(profile_data) # Merge kwargs into profile return profile # Different callers pass different data user1 = create_user_profile( "Jatin", age=25, city="Gurugram", email="jatin@gmail.com" ) print(user1) # {'name': 'Jatin', 'age': 25, 'city': 'Gurugram', 'email': 'jatin@gmail.com'} user2 = create_user_profile( "Priya", phone="9876543210", profession="Data Analyst" ) print(user2) # {'name': 'Priya', 'phone': '9876543210', 'profession': 'Data Analyst'} # Unpack dict into **kwargs using ** data = {"age": 30, "city": "Delhi", "role": "Manager"} user3 = create_user_profile("Rahul", **data) print(user3) # {'name': 'Rahul', 'age': 30, 'city': 'Delhi', 'role': 'Manager'}

πŸ“‹ Parameter Order Rule:

CORRECT ORDER in function definition: def func(regular, *args, default_arg=value, **kwargs): ↑ ↑ ↑ ↑ Required Variable pos. Default Variable keyword
Example:
def process(name, *tags, active=True, **metadata):
...

Call:
process("Jatin", "python", "sql", active=False, city="Delhi", age=25)
↑ ↑ ↑ ↑ ↑ ↑
name tags→(...) default active=False metadata→{...}
πŸ“‹ Real-World Use: **kwargs flexible APIs banane mein bahut useful hai. Pandas mein pd.read_csv(**options), Requests library mein requests.get(url, **headers), Django views mein func(request, **kwargs). Jab function ke arguments future mein add ho sakte hain β€” kwargs future-proof hai. Existing code break nahi karta.

πŸ’¬ Interview Q&A:

Q: *args aur **kwargs mein kya difference hai?
Ans: Dono variable arguments handle karte hain lekin different type: (1) *args variable POSITIONAL arguments β€” Tuple mein pack hote hain. Example: func(1, 2, 3) β†’ args = (1, 2, 3). (2) **kwargs variable KEYWORD arguments β€” Dictionary mein pack hote hain. Example: func(a=1, b=2) β†’ kwargs = {"a": 1, "b": 2}. args = list-like, kwargs = dict-like. Dono ek saath use kar sakte ho β€” def func(*args, **kwargs) β€” maximum flexibility.

Q: Function definition mein parameters ka correct order kya hai?
Ans: Strict order: Regular parameters β†’ *args β†’ Default parameters β†’ **kwargs. Example: def func(name, *tags, active=True, **metadata). Reason: Python argument binding left-to-right hota hai. Agar order break karo toh SyntaxError. Rule of thumb: (1) Required positional pehle, (2) *args extra positional ke liye, (3) Default keyword-only, (4) **kwargs last mein. Interview mein yeh order 100% puchha jaata hai!

7. Return Multiple Values 🟑

πŸ“˜ Definition: Python allows functions to return multiple values by separating them with commas in the return statement. Internally, Python packs these values into a TUPLE and returns it. The caller can either receive the entire tuple or unpack the values into separate variables. This is a Python-specific feature β€” most languages require returning a struct, class, or array.

🎯 Samjho Hinglish Mein: Kabhi tumhe ek function se ek se zyada values chahiye hoti hain. Jaise divide() function karo β€” quotient bhi chahiye aur remainder bhi. Python mein return quotient, remainder likh do β€” dono values ek saath return ho jaayengi. Receive karne ke 2 tarike hain: (1) Ek variable mein β€” tuple milega. (2) Do variables mein β€” automatic unpacking. Java/C++ mein yeh possible nahi β€” Python special hai!

πŸ’» Examples:

# Example 1: Return multiple values (as tuple) def divide(a, b): quotient = a // b remainder = a % b return quotient, remainder # Comma separated β†’ tuple
# Method 1: Receive as tuple
result = divide(17, 5)
print(result) # (3, 2)
print(type(result)) # 
print(result[0]) # 3 (quotient)

# Method 2: Unpack into variables (Pythonic!)
q, r = divide(17, 5)
print(f"Quotient: {q}, Remainder: {r}")
# Quotient: 3, Remainder: 2
# Example 2: Statistics function β€” multiple metrics def calculate_stats(numbers): total = sum(numbers) count = len(numbers) average = total / count max_val = max(numbers) min_val = min(numbers) return total, count, average, max_val, min_val # Unpack into 5 variables at once scores = [85, 92, 78, 96, 88] total, count, avg, high, low = calculate_stats(scores) print(f"Total: {total}") # Total: 439 print(f"Count: {count}") # Count: 5 print(f"Average: {avg}") # Average: 87.8 print(f"Highest: {high}") # Highest: 96 print(f"Lowest: {low}") # Lowest: 78
# Example 3: Return dict for named values (better for many returns) def analyze_employee(salary, years): bonus = salary * 0.10 tax = salary * 0.20 net = salary - tax + bonus return { "gross_salary": salary, "bonus": bonus, "tax": tax, "net_salary": net, "experience": years } # Access by name β€” more readable than tuple index result = analyze_employee(50000, 3) print(f"Net Salary: β‚Ή{result['net_salary']}") print(f"Bonus: β‚Ή{result['bonus']}") # Net Salary: β‚Ή45000.0 # Bonus: β‚Ή5000.0
πŸ“‹ Best Practice: 2-3 values return karne hain β†’ tuple unpacking clean hai. 4+ values return karne hain β†’ dictionary ya class use karo β€” code readable rahega. Named values ke saath maintainability better hoti hai. Interview mein bata sakte ho ki "for many return values, dictionary or dataclass is cleaner than tuples."

πŸ’¬ Interview Q&A:

Q: Python function multiple values kaise return karta hai?
Ans: Python return a, b, c mein internally values ko TUPLE mein pack karta hai β€” (a, b, c) return hota hai. Caller do tarike se receive kar sakta hai: (1) Ek variable mein pura tuple: result = func(). (2) Multiple variables mein unpack: x, y, z = func(). Yeh Python-specific feature hai β€” Java/C++ mein possible nahi (wahan struct/class use karna padta hai). 4+ values ke liye dictionary ya class better hai readability ke liye.

8. Scope β€” Local vs Global (LEGB Rule) πŸ”΄

πŸ“˜ Definition: Scope defines WHERE a variable is accessible in the code. Python follows the LEGB Rule: Local (inside current function) β†’ Enclosing (outer function if nested) β†’ Global (module level) β†’ Built-in (Python built-ins like print, len). Python searches for a variable in this exact order. To modify a global variable inside a function, use global keyword. For enclosing scope, use nonlocal.

🎯 Samjho Hinglish Mein: Scope = "kahan variable exist karta hai." LEGB rule ka matlab β€” Python variable dhundhne mein 4 places check karta hai in order: (1) Local β€” abhi wale function ke andar. (2) Enclosing β€” bahar wale function mein (agar nested). (3) Global β€” module level (function ke bahar). (4) Built-in β€” Python ka default (print, len, etc.). Local variable ko function ke bahar access nahi kar sakte. Global ko function ke andar READ kar sakte ho, MODIFY karne ke liye global keyword chahiye.

πŸ“‹ LEGB Rule Visualized:

Python variable lookup order:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ 4. BUILT-IN Scope β”‚ ← print(), len(), sum()
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ (Python's built-ins)
β”‚ β”‚ 3. GLOBAL Scope β”‚ β”‚
β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ ← Module-level variables
β”‚ β”‚ β”‚ 2. ENCLOSING Scope β”‚ β”‚ β”‚ (outside all functions)
β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ 1. LOCAL Scope β”‚ β”‚ β”‚ β”‚ ← Outer function (nested)
β”‚ β”‚ β”‚ β”‚ x = 10 ← Found! β”‚ β”‚ β”‚ β”‚ ← Inside current function
β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚
β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Python STOPS as soon as variable is found in innermost scope.

πŸ’» Examples:

# Example 1: Local vs Global message = "I am GLOBAL" # Global scope
def show():
message = "I am LOCAL" # Local scope (different!)
print(message)

show() # I am LOCAL (uses local)
print(message) # I am GLOBAL (unchanged!)

# Local variable dies when function ends
# print(message inside show()) β€” Not accessible outside!
# Example 2: global keyword β€” modify global variable counter = 0 # Global def increment_wrong(): counter = counter + 1 # ❌ Error! (trying to modify global) def increment_right(): global counter # βœ… Declare global first counter = counter + 1 # increment_wrong() β†’ UnboundLocalError increment_right() increment_right() increment_right() print(counter) # 3 (global counter modified!)
# Example 3: LEGB in action β€” nested functions x = "Global X" # Global def outer(): x = "Enclosing X" # Enclosing def inner(): x = "Local X" # Local (found first!) print(f"Inner: {x}") inner() print(f"Outer: {x}") # Uses enclosing X outer() print(f"Module: {x}") # Uses global X # Output: # Inner: Local X # Outer: Enclosing X # Module: Global X # nonlocal β€” modify enclosing scope def counter_factory(): count = 0 # Enclosing def increment(): nonlocal count # Modify enclosing (not global!) count += 1 return count return increment my_counter = counter_factory() print(my_counter()) # 1 print(my_counter()) # 2 print(my_counter()) # 3
⚠️ Best Practice: global keyword ka use MINIMIZE karo β€” global variables debugging nightmare hote hain, unpredictable side effects. Better approaches: (1) Function parameters pass karo. (2) Values return karo, caller assign kare. (3) Class use karo state manage karne ke liye. Global variables sirf tab jab absolutely zaroori ho (jaise constants, config).

πŸ’¬ Interview Q&A:

Q: LEGB Rule kya hai?
Ans: LEGB = Python ka variable lookup order β€” Local, Enclosing, Global, Built-in. Jab tum variable use karte ho, Python is exact order mein dhundhta hai: (1) Local β€” current function ke andar. (2) Enclosing β€” outer function (nested case). (3) Global β€” module level. (4) Built-in β€” Python's built-in functions/names (print, len, sum). Variable pehle innermost scope mein milte hi Python search stop kar deta hai. Isliye local variable global same-name variable ko "shadow" kar sakta hai.

Q: global aur nonlocal keyword mein kya difference hai?
Ans: Dono keywords function ke andar OUTER scope ke variables modify karne ke liye hain. global β€” GLOBAL scope (module level) ka variable modify karta hai. nonlocal β€” ENCLOSING scope (outer function in nested case) ka variable modify karta hai. Bina keyword ke β€” outer variable ko sirf READ kar sakte ho, MODIFY karne ki koshish karoge toh Python naya local variable bana dega. nonlocal Python 3.0+ mein aaya β€” closures aur decorators mein bahut use hota hai.

9. Lambda Functions β€” Anonymous Functions πŸ”΄

πŸ“˜ Definition: A Lambda function is a small, anonymous (nameless) function defined using the lambda keyword. Syntax: lambda arguments: expression. Lambda functions are limited to a SINGLE expression β€” no statements, no multiple lines. They are used for short, one-time operations, especially with map(), filter(), sorted(), and Pandas operations. Also called "lambda expressions" or "arrow functions" in other languages.

🎯 Samjho Hinglish Mein: Lambda = mini function without a name. Jab tumhe bahut chota function chahiye β€” sirf ek line ka β€” aur naam dena bhi zaroori nahi (one-time use), tab lambda use karo. lambda x: x * 2 = ek function jo x le kar 2x return karta hai. Bina def, bina return likhe. Pandas mein df.apply(lambda x: x*2) bahut common hai. Regular function likhne se bachne ka shortcut hai lambda.

πŸ“‹ Lambda vs Regular Function:

Feature Regular Function (def) Lambda Function
Name Has a name Anonymous (no name)
Body Multiple statements, multi-line Single expression only
return Explicit return needed Implicit return (auto)
Docstring Yes No
Best For Complex logic, reusable Simple, one-time operations

πŸ’» Examples:

# Example 1: Basic Lambda
# Regular function
def square(x):
return x ** 2

# Lambda equivalent (one line!)
square_lambda = lambda x: x ** 2

print(square(5)) # 25
print(square_lambda(5)) # 25 (same result!)

# Lambda with multiple arguments
add = lambda a, b: a + b
multiply = lambda x, y, z: x * y * z

print(add(10, 20)) # 30
print(multiply(2, 3, 4)) # 24
# Example 2: Lambda with sorted() β€” custom sorting students = [ {"name": "Jatin", "score": 85}, {"name": "Priya", "score": 92}, {"name": "Rahul", "score": 78} ] # Sort by score (descending) using lambda sorted_students = sorted(students, key=lambda s: s["score"], reverse=True) for s in sorted_students:
     print(s) # {'name': 'Priya', 'score': 92} # {'name': 'Jatin', 'score': 85} # {'name': 'Rahul', 'score': 78} # Sort by name length names = ["Jatin", "Priya", "Rahul Kumar", "Ne"] print(sorted(names, key=lambda x: len(x))) # ['Ne', 'Jatin', 'Priya', 'Rahul Kumar']
# Example 3: Lambda with conditional (ternary) # Lambda with if-else grade = lambda score: "Pass" if score >= 40 else "Fail" print(grade(75)) # Pass print(grade(35)) # Fail # Multi-condition lambda category = lambda age: ( "Child" if age < 13 else "Teen" if age < 20 else "Adult" if age < 60 else "Senior" ) print(category(10)) # Child print(category(17)) # Teen print(category(45)) # Adult print(category(65)) # Senior
⚠️ When NOT to use Lambda: (1) Complex logic β€” use regular def. (2) Multiple statements needed. (3) Documentation needed (lambda mein docstring nahi). (4) Reusability chahiye β€” named function better hai. Rule: Agar function ka description likhne mein 2 lines lag rahi hain β€” lambda nahi, def use karo. PEP 8 kehta hai β€” don't assign lambda to a variable, use def instead.

πŸ’¬ Interview Q&A:

Q: Lambda function kya hai aur def se kaise different hai?
Ans: Lambda = anonymous (nameless) single-expression function using lambda keyword. Syntax: lambda args: expression. Differences from def: (1) Nameless. (2) Single expression only β€” statements allowed nahi. (3) Implicit return (koi return keyword nahi likhna). (4) No docstring. Best for one-time, simple operations β€” especially with sorted(), map(), filter(), and Pandas apply(). Complex logic ke liye def use karo.

Q: Lambda ka real-world use case kya hai?
Ans: Sabse common use cases: (1) sorted()/list.sort() ke key parameter mein custom sorting β€” sorted(items, key=lambda x: x.price). (2) map() β€” transform items β€” map(lambda x: x*2, list). (3) filter() β€” filter items β€” filter(lambda x: x>0, list). (4) Pandas apply() β€” column transformations β€” df['new'] = df['col'].apply(lambda x: x.upper()). Lambda ka main advantage β€” inline definition, koi separate function likhne ki zaroorat nahi.

10. map(), filter(), reduce() with Lambda πŸ”΄

πŸ“˜ Definition: These are functional programming tools that operate on iterables (lists, tuples). map(func, iterable) applies a function to EACH item β€” returns a new iterable. filter(func, iterable) keeps only items where function returns True. reduce(func, iterable) (from functools) reduces the iterable to a SINGLE value by applying function cumulatively. All three work beautifully with Lambda functions.

🎯 Samjho Hinglish Mein: Teen functional tools β€” sab list par kaam karte hain, tarike alag: (1) map() β€” har item par function apply karo (transform). "Har number ko square karo." (2) filter() β€” sirf woh items rakho jo condition satisfy karein. "Sirf positive numbers rakho." (3) reduce() β€” sab items ko combine karke ek value banao. "Saare numbers ka product nikalo." Lambda ke saath yeh super powerful hain β€” ek line mein complex operations ho jaate hain.

πŸ’» Examples:

# Example 1: map() β€” Transform each item numbers = [1, 2, 3, 4, 5]
# Square each number
squared = list(map(lambda x: x ** 2, numbers))
print(squared)
# [1, 4, 9, 16, 25]

# Convert temperatures Celsius β†’ Fahrenheit
celsius = [0, 25, 30, 40, 100]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(fahrenheit)
# [32.0, 77.0, 86.0, 104.0, 212.0]

# Convert names to uppercase
names = ["jatin", "priya", "rahul"]
upper_names = list(map(lambda n: n.upper(), names))
print(upper_names)
# ['JATIN', 'PRIYA', 'RAHUL']

map() with multiple iterables β€” element-wise operation
list1 = [1, 2, 3]
list2 = [10, 20, 30]
sums = list(map(lambda a, b: a + b, list1, list2))
print(sums) # [11, 22, 33]
# Example 2: filter() β€” Keep only matching items numbers = [1, -2, 3, -4, 5, 6, -7, 8] # Only positive numbers positives = list(filter(lambda x: x > 0, numbers)) print(positives) # [1, 3, 5, 6, 8] # Only even numbers evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [-2, -4, 6, 8] # Real world β€” filter passing students students = [ {"name": "Jatin", "score": 85}, {"name": "Priya", "score": 32}, {"name": "Rahul", "score": 78}, {"name": "Neha", "score": 45} ] passed = list(filter(lambda s: s["score"] >= 40, students)) for student in passed:
     print(student) # {'name': 'Jatin', 'score': 85} # {'name': 'Rahul', 'score': 78} # {'name': 'Neha', 'score': 45}
# Example 3: reduce() β€” Reduce to single value from functools import reduce numbers = [1, 2, 3, 4, 5] # Sum all numbers total = reduce(lambda a, b: a + b, numbers) print(total) # 15 (same as sum()) # Product of all numbers (factorial) product = reduce(lambda a, b: a * b, numbers) print(product) # 120 (1*2*3*4*5) # Find maximum maximum = reduce(lambda a, b: a if a > b else b, numbers) print(maximum) # 5 # Concatenate strings words = ["Hello", "World", "Python"] sentence = reduce(lambda a, b: a + " " + b, words) print(sentence) # Hello World Python # With initial value (starts with 100) total_with_start = reduce(lambda a, b: a + b, numbers, 100) print(total_with_start) # 115 (100 + 15)
πŸ“‹ Modern Alternative β€” List Comprehension: Python community actually list comprehension prefer karti hai map/filter se β€” zyada readable. Compare:
β€’ list(map(lambda x: x*2, nums)) β†’ [x*2 for x in nums] βœ…
β€’ list(filter(lambda x: x>0, nums)) β†’ [x for x in nums if x>0] βœ…
Interview mein dono batao β€” map/filter functional programming style hai, list comprehension Pythonic hai. Reduce ke liye direct alternative nahi hai β€” sum(), max(), min() specific cases mein.

πŸ’¬ Interview Q&A:

Q: map(), filter(), reduce() mein kya difference hai?
Ans: Teeno iterables par kaam karte hain, alag purpose: (1) map(func, iter) β€” har item par function apply karke NEW iterable return karta hai. Same length. Transformation ke liye. (2) filter(func, iter) β€” sirf woh items rakhta hai jinke liye function True return kare. Length change ho sakti hai. Filtering ke liye. (3) reduce(func, iter) β€” cumulative operation se saari items ko ek SINGLE value mein reduce karta hai. functools se import karna padta hai. Aggregation ke liye. Modern Python mein list comprehension aur built-in functions (sum, max) prefer kiye jaate hain.

11. Decorators Basics πŸ”΄

πŸ“˜ Definition: A Decorator is a function that MODIFIES the behavior of another function WITHOUT changing its actual code. Decorators use the @decorator_name syntax placed above the function definition. They are commonly used for logging, timing, authentication, caching, and validation. Decorators are based on Python's ability to treat functions as "first-class citizens" β€” functions can be passed as arguments, returned from other functions, and assigned to variables.

🎯 Samjho Hinglish Mein: Decorator = function ke upar ek "wrapper" jo extra kaam karta hai bina original function ko modify kiye. Jaise cake ke upar cream lagana β€” cake same rehta hai, upar se decoration add ho jaata hai. Example: kisi function ke start aur end mein log messages add karne hain β€” har function mein manually print() likhne ki jagah, ek decorator banao aur @log laga do β€” done! Django/Flask mein @app.route(), testing mein @pytest.fixture β€” sab decorators hain.

πŸ’» Examples:

# Example 1: Simple decorator β€” add logging def my_logger(func): def wrapper(*args, **kwargs): print(f"πŸ”΅ Calling: {func.__name__}") result = func(*args, **kwargs) # Call original print(f"🟒 Finished: {func.__name__}") return result return wrapper
# Apply decorator with @ syntax
@my_logger
def greet(name):
print(f"Hello, {name}!")

greet("Jatin")
# πŸ”΅ Calling: greet
# Hello, Jatin!
# 🟒 Finished: greet
# Example 2: Timing decorator β€” measure execution time import time def measure_time(func):
     def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"⏱️ {func.__name__} took {end-start:.4f} seconds") return result return wrapper @measure_time def slow_operation(): time.sleep(1) # Simulate slow work return "Done!" @measure_time def fast_operation():
     return sum(range(1000)) slow_operation() # ⏱️ slow_operation took 1.0012 seconds fast_operation() # ⏱️ fast_operation took 0.0001 seconds
# Example 3: Authentication decorator (real-world) current_user = {"role": "admin"} # Simulated logged-in user def requires_admin(func):
     def wrapper(*args, **kwargs):
     if current_user["role"] != "admin":
     print("❌ Access denied! Admin only.") return None return func(*args, **kwargs) return wrapper @requires_admin def delete_all_data():
     print("πŸ—‘οΈ All data deleted!") @requires_admin def view_reports():
     print("πŸ“Š Reports shown") delete_all_data() # πŸ—‘οΈ All data deleted! view_reports() # πŸ“Š Reports shown # Change user role β€” test again current_user["role"] = "guest" delete_all_data() # ❌ Access denied! Admin only.
πŸ“‹ Where You'll See Decorators:
β€’ Flask/Django: @app.route('/home') β€” URL routing
β€’ Pytest: @pytest.fixture β€” test setup
β€’ Python built-in: @staticmethod, @classmethod, @property
β€’ Functools: @lru_cache β€” memoization for performance
Real-world Python code mein decorators everywhere hain β€” samajhna zaroori hai!

πŸ’¬ Interview Q&A:

Q: Decorator kya hai aur kaise kaam karta hai?
Ans: Decorator ek function hai jo doosre function ko INPUT leta hai, uske BEHAVIOR ko modify karta hai, aur MODIFIED function return karta hai β€” bina original function ka code change kiye. @decorator_name syntax function ke upar likha jaata hai. Internally @my_dec above def func() is equivalent to func = my_dec(func). Uses: logging, timing, authentication, caching, input validation. Yeh Python ke "functions as first-class objects" concept par based hai β€” functions ko variables ki tarah pass aur return kar sakte ho.

12. Docstrings & Type Hints πŸ”΄

πŸ“˜ Definition: Docstrings are string literals placed as the FIRST statement in a function to describe what the function does. They are accessible via function.__doc__ and used by help(). Type Hints (Python 3.5+) allow you to specify the expected data types of parameters and return values using colons. They don't enforce types at runtime but help IDEs, linters, and other developers understand your code better.

🎯 Samjho Hinglish Mein: Docstring = function ka description β€” kya karta hai, kya inputs leta hai, kya return karta hai. Triple quotes mein likhte hain function ke andar first line par. Type Hints = function ke parameters aur return value ka data type explicitly batana β€” def add(a: int, b: int) -> int. Python actually check nahi karta types at runtime (dynamically typed hai) β€” lekin IDEs, editors, aur tools like mypy use karte hain warnings dene ke liye. Professional Python code mein type hints standard hain aaj kal.

πŸ’» Examples:

# Example 1: Docstrings def calculate_area(radius): """ Calculate the area of a circle.
text

Args:
    radius (float): The radius of the circle.

Returns:
    float: The area of the circle (Ο€ Γ— rΒ²).

Example:
    >>> calculate_area(5)
    78.53981633974483
"""
import math
return math.pi * radius ** 2
# Access docstring
print(calculate_area.doc)

# Use built-in help()
help(calculate_area)
# Shows full documentation!
# Example 2: Type Hints (basic) def add(a: int, b: int) -> int: """Add two integers and return the sum.""" return a + b def greet(name: str, greeting: str = "Hello") -> str: """Return a greeting message.""" return f"{greeting}, {name}!" def is_adult(age: int) -> bool: """Check if a person is an adult.""" return age >= 18 def no_return_value() -> None: """This function doesn't return anything.""" print("Just printing...") # Type hints are NOT enforced at runtime! print(add("Hello", " World")) # Still runs β†’ "Hello World" (Python doesn't check types) # But IDE will show warning!
# Example 3: Advanced Type Hints (professional code) from typing import List, Dict, Optional, Tuple, Union # List of integers def calculate_sum(numbers: List[int]) -> int: """Sum all numbers in a list.""" return sum(numbers) # Dictionary def process_user(user: Dict[str, any]) -> str: """Process user dictionary and return formatted string.""" return f"{user['name']} ({user['age']})" # Optional β€” value can be None def find_user(user_id: int) -> Optional[str]: """Return user name or None if not found.""" users = {1: "Jatin", 2: "Priya"} return users.get(user_id) # Returns None if not found # Union β€” accepts multiple types def display(value: Union[int, float, str]) -> None: """Display value regardless of type.""" print(f"Value: {value}") # Multiple returns as tuple def divide(a: int, b: int) -> Tuple[int, int]: """Return quotient and remainder.""" return a // b, a % b # Use them print(calculate_sum([1, 2, 3, 4, 5])) # 15 print(find_user(1)) # Jatin print(find_user(99)) # None q, r = divide(17, 5) print(f"Q: {q}, R: {r}") # Q: 3, R: 2
πŸ“‹ Best Practices: Professional Python code mein: (1) Har public function mein docstring likho β€” team members ke liye critical. (2) Type hints add karo β€” bug catch early, IDE autocomplete better. (3) Use mypy for static type checking. (4) Follow PEP 257 for docstring conventions. Modern Python (3.9+) mein type hints simplified β€” list[int] directly likh sakte ho, List[int] import karne ki zaroorat nahi.

πŸ’¬ Interview Q&A:

Q: Docstrings aur comments mein kya difference hai?
Ans: Comments (# se) developers ke liye code ke andar nots hote hain β€” runtime mein ignore hote hain, accessible nahi hain externally. Docstrings triple-quoted strings hain jo function/class ki DOCUMENTATION describe karti hain β€” function.__doc__ se access hoti hain, help(function) se dikhti hain, aur automatic documentation tools (Sphinx) use karte hain. Comments internal logic explain karte hain, docstrings API describe karte hain (kya karta hai, kaise use karna hai). Professional code mein dono use hote hain.

Q: Type hints kya karte hain? Python dynamically typed hai β€” phir type hints kyun?
Ans: Type hints Python 3.5+ ka feature hai β€” parameters aur return values ka expected type batata hai. Python RUNTIME par types check nahi karta (dynamically typed hi rehti hai) β€” hints sirf documentation aur tooling ke liye hain. Benefits: (1) IDE autocomplete aur error detection better. (2) mypy jaisi tools se static type checking kar sakte ho. (3) Code more readable aur self-documenting banti hai. (4) Refactoring safer hoti hai. Large codebases (Django projects, data pipelines) mein type hints industry standard hain aaj kal.

Quick Revision β€” Functions Complete Summary

# Topic Key Takeaway
1Functions Introdef, call, return β€” reusability, modularity, readability (DRY)
2Parameters vs ArgsParameters = placeholders (def), Arguments = values (call)
3Default ParametersDefault value if not provided. Rule: defaults AFTER non-defaults. Beware mutable defaults!
4Keyword ArgumentsPass by name (name="x") β€” order doesn't matter. More readable.
5*argsVariable positional args β†’ packed into TUPLE
6**kwargsVariable keyword args β†’ packed into DICT. Order: regular, *args, defaults, **kwargs
7Multiple Returnsreturn a, b, c β†’ tuple. Unpack: x, y, z = func(). 4+ values β†’ use dict.
8Scope (LEGB)Local β†’ Enclosing β†’ Global β†’ Built-in. Use global/nonlocal to modify outer scopes.
9LambdaAnonymous single-expression function. Use with sorted, map, filter, pandas apply.
10map/filter/reduceTransform / Filter / Aggregate. List comprehension often more Pythonic.
11Decorators@decorator β€” modify function behavior. Uses: logging, timing, auth, caching.
12Docstrings & Type Hints"""Docstring""" for documentation. def func(x: int) -> str for type hints (not enforced).

Next: Python Handbook β€” Part 9

Agle chapter mein hum cover karenge: File Handling & Exception Handling β€” open(), read/write files (txt, csv, json), with statement (context manager), try/except/finally, custom exceptions, raise statement. Real-world data processing ke liye critical topics. Part 1-8 Data Insights par available hain β€” Python Basics se lekar Functions tak complete deep dive.

Happy Learning & Keep Coding! πŸš€

πŸ‘€
Jatin Kumar
Data Analyst & Educator

Python, SQL, Power BI aur Excel mein practical tutorials likhta hoon β€” taaki data analytics seekhna aasan ho. Portfolio: jatinanalytics.co.in

Portfolio LinkedIn GitHub Kaggle All Articles
Share:

πŸ’¬ Comments (0)

Spam/links allowed nahi hain β€” respectful comments welcome!

Loading comments...

Was this article helpful?
Previous ArticleControl Flow β€” if/elif/else & LoopsNext Article Complete Pyhton Cheat sheet For Data Analytics

πŸ“š More Articles Like This

How to Fix Python TypeError β€” Complete Guide

Read Article

File Handling & Exceptions

Read Article

Dictionaries Explained: Complete Guide with Examples (2026)

Read Article