Python Notes
HubHistory of Python - Complete Guide 2026Python Applications - Complete Guide 2026Python Features - Complete Guide 2026What is Python? - Complete Guide 2026Why Learn Python? - Complete Guide 2026Your First Python Program – Hello World & Beyond 2026How to Install Python on Windows, Mac & Linux – Complete Guide 2026Install VS Code for Python – Complete Setup Guide with Extensions 2026Python Environment Setup – Virtual Environments, pip & Project Structure 2026Python IDLE – Complete Guide for Beginners 2026Python CommentsPython Data TypesPython Input and OutputPython OperatorsPython SyntaxPython Strings BasicsPython Type CastingPython VariablesBreak, Continue and Pass in PythonElif Statement in PythonFor Loop in PythonIf-Else Statement in PythonIf Statement in PythonNested If in PythonPattern Programs in PythonWhile Loop in PythonDecorators in PythonFunction Arguments in PythonFunctions Basics in PythonGenerators in PythonLambda Functions in PythonRecursive Functions in PythonReturn Statement in PythonScope of Variables in PythonAbstraction in PythonClasses and Objects in PythonConstructors in PythonEncapsulation in PythonInheritance in PythonMagic Methods (Dunder Methods) in PythonMethod Overriding in PythonPolymorphism in PythonPython Comprehensions – List, Dict, Set & GeneratorPython Dictionaries – Key-Value StorePython Dictionary Methods – Complete ReferencePython List Methods – All Built-in MethodsPython Lists – Complete GuidePython Set Methods – Complete ReferencePython Sets – Unordered Unique CollectionsPython Tuples – Immutable SequencesPython Asynchronous Programming with asyncioPython Context ManagersAdvanced Python DecoratorsAdvanced Python GeneratorsPython Iterators - Advanced GuidePython Memory ManagementPython MultiprocessingPython MultithreadingCRUD Operations in Python DatabasesMySQL with Python (mysql-connector-python)ORM Introduction with SQLAlchemyPostgreSQL with Python (psycopg2)SQLite3 with PythonIntroduction to DjangoDjango Models and ORMDjango REST API with DRFDjango ViewsIntroduction to FlaskFlask RoutingFlask Templates with Jinja2Email Automation with PythonPDF Automation with PythonSelenium Web Automation with PythonTask Scheduler with PythonWeb Scraping with PythonData Analysis with PythonData Cleaning with PythonData Visualization ProjectData Visualization with MatplotlibNumPy IntroductionPandas IntroductionStatistical Visualization with SeabornClassification AlgorithmsClustering AlgorithmsIntroduction to Machine LearningMachine Learning Project: Churn PredictionModel Evaluation and SelectionRegression AlgorithmsSave pipeline (includes preprocessing + model)AI Assistant ProjectCalculator ProjectChatbot ProjectExpense Tracker ProjectFace Detection ProjectPassword Generator ProjectWeather App ProjectPython Coding Interview QuestionsPython OOP Interview Questions and AnswersPython Master CheatsheetPython Interview Questions and AnswersPython Best PracticesCommon Python Errors and SolutionsPython Debugging TechniquesPython Learning Resources
Python mein functions ki complete guide — definition, calling, types, aur best practices. Samjho functions ka syntax, purpose, aur real-world usage Hindi explanations ke saath.
Functions ek reusable block of code hota hai jo ek specific task perform karta hai. Ek baar define karo, baar baar use karo — yahi hai programming ka golden rule!
🔤 Function Define Karna (Defining a Function)
python example
# Basic syntax
def function_name(parameters):
"""Docstring — function ka description"""
# function body
# code logic yahan likhte hain
return value # optional📝 Pehla Function — Hello World!
Example
# ─────────────────────────────────────
# Sabse simple function
# ─────────────────────────────────────
def greet():
"""Ek simple greeting print karta hai"""
print("Namaste, Python Seekhne Wale! 🙏")
# Function ko call karna
greet()
Example
# OUTPUT:
Namaste, Python Seekhne Wale! 🙏
🏗️ Function Anatomy (Function ke Parts)
Example
# ─────────────────────────────────────
# Function ke sabhi parts ka example
# ─────────────────────────────────────
#
# def greet_user ( name ) :
# │ │ │
# │ │ └── Parameter (input variable)
# │ └──────────── Function naam
# └────────────────── Keyword
def greet_user(name):
"""
User ko greet karta hai.
Args:
name (str): User ka naam
Returns:
str: Greeting message
"""
message = f"Hello, {name}! Python seekhna start karo aaj se! 🚀"
return message
# Call karna
result = greet_user("Rahul")
print(result)
Example
# OUTPUT:
Hello, Rahul! Python seekhna start karo aaj se! 🚀
📚 Function ke Types (Types of Functions)
| Built-in | User-Defined | |||
|---|---|---|---|---|
| Functions | Functions | |||
| print() | def my_func(): | |||
| len() | ... | |||
| range() | ||||
| type() | ||||
| input() | ||||
| Lambda | Recursive | |||
| Functions | Functions | |||
| lambda x: x*2 | def fact(n): | |||
| return n*fact(n-1) |
🔧 Built-in Functions (Pehle se Bane Functions)
Example
# ─────────────────────────────────────
# Python ke built-in functions
# ─────────────────────────────────────
# 1. print() — output dikhana
print("Jai Hind! 🇮🇳")
# 2. len() — length nikalna
fruits = ["aam", "kela", "angoor"]
print(len(fruits)) # 3
# 3. type() — data type check karna
age = 25
print(type(age)) # <class 'int'>
# 4. range() — numbers ki range banana
for i in range(1, 6):
print(i, end=" ") # 1 2 3 4 5
print()
# 5. abs() — absolute value
print(abs(-42)) # 42
# 6. max() aur min()
numbers = [10, 5, 8, 3, 15]
print(max(numbers)) # 15
print(min(numbers)) # 3
# 7. sum()
print(sum(numbers)) # 41
# 8. sorted()
print(sorted(numbers)) # [3, 5, 8, 10, 15]
# 9. input() — user se input lena
# naam = input("Apna naam batao: ") # (interactive mein use karo)
# 10. int(), float(), str() — type conversion
price = "199"
price_int = int(price)
print(price_int + 1) # 200
Example
# OUTPUT:
Jai Hind! 🇮🇳
3
<class 'int'>
1 2 3 4 5
42
15
3
41
[3, 5, 8, 10, 15]
200
🛠️ User-Defined Functions (Apne Functions Banao)
Example
# ─────────────────────────────────────
# 1. No Parameter, No Return Value
# ─────────────────────────────────────
def show_divider():
"""Screen pe divider line print karta hai"""
print("=" * 50)
show_divider()
print("Python Functions Basics")
show_divider()
Example
# OUTPUT:
==================================================
Python Functions Basics
==================================================
Example
# ─────────────────────────────────────
# 2. Parameter ke saath, No Return
# ─────────────────────────────────────
def display_student(name, age, city):
"""Student ki info display karta hai"""
print(f"📚 Student Name : {name}")
print(f"🎂 Age : {age} saal")
print(f"🏙️ City : {city}")
print("-" * 30)
display_student("Priya", 20, "Delhi")
display_student("Rohan", 22, "Mumbai")
| 📚 Student Name | Priya |
| 🎂 Age | 20 saal |
| 🏙️ City | Delhi |
| 📚 Student Name | Rohan |
| 🎂 Age | 22 saal |
| 🏙️ City | Mumbai |
Example
# ─────────────────────────────────────
# 3. Parameter + Return Value ke saath
# ─────────────────────────────────────
def calculate_area(length, width):
"""Rectangle ka area calculate karta hai"""
area = length * width
return area
room_area = calculate_area(12, 8)
print(f"Kamre ka area: {room_area} square feet")
# Direct use bhi kar sakte hain
print(f"Hall ka area: {calculate_area(20, 15)} square feet")
Example
# OUTPUT:
Kamre ka area: 96 square feet
Hall ka area: 300 square feet
📖 Docstrings — Function Documentation
Example
# ─────────────────────────────────────
# Docstring likhna — best practice hai
# ─────────────────────────────────────
def celsius_to_fahrenheit(celsius):
"""
Celsius ko Fahrenheit mein convert karta hai.
Formula: F = (C × 9/5) + 32
Args:
celsius (float): Temperature in Celsius
Returns:
float: Temperature in Fahrenheit
Example:
>>> celsius_to_fahrenheit(100)
212.0
>>> celsius_to_fahrenheit(0)
32.0
"""
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
# Use karo
temp_c = 37 # Normal body temperature
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C = {temp_f}°F")
# Docstring padhna
print("\n📖 Function Documentation:")
print(celsius_to_fahrenheit.__doc__)
| Formula | F = (C × 9/5) + 32 |
| celsius (float) | Temperature in Celsius |
| float | Temperature in Fahrenheit |
🔄 Functions Call Kaise Kaam Karta Hai (Call Stack)
┌─────────────────────────────────────────────┐
│ CALL STACK DIAGRAM │
│ │
│ main() calls greet() │
│ │
│ ┌─────────────────┐ │
│ │ main() │ ← Program start │
│ │ ... │ │
│ │ greet("Ali") ─┼──► ┌──────────────┐ │
│ │ ... │ │ greet("Ali")│ │
│ │ ... │ │ print(...) │ │
│ │ ... │◄───┼─ return │ │
│ └─────────────────┘ └──────────────┘ │
│ │
│ Stack grows UP when function called │
│ Stack shrinks DOWN when function returns │
└─────────────────────────────────────────────┘
Example
# ─────────────────────────────────────
# Call Stack ka practical example
# ─────────────────────────────────────
def step_3():
print(" 🔵 Step 3: Final calculation")
return 100
def step_2():
print(" 🟡 Step 2: Processing...")
result = step_3()
return result * 2
def step_1():
print("🟢 Step 1: Starting process")
value = step_2()
print(f" ✅ Got value: {value}")
return value
# Execute
final = step_1()
print(f"\n🎯 Final Result: {final}")
| 🟢 Step 1 | Starting process |
| 🟡 Step 2 | Processing... |
| 🔵 Step 3 | Final calculation |
| ✅ Got value | 200 |
| 🎯 Final Result | 200 |
🎯 DRY Principle — Don't Repeat Yourself
Example
# ─────────────────────────────────────
# BAD CODE — DRY principle violate kar raha hai
# ─────────────────────────────────────
# ❌ Yeh mat karo
print("Rahul ki age: 20")
print("Rahul ki city: Delhi")
print("---")
print("Priya ki age: 22")
print("Priya ki city: Mumbai")
print("---")
print("Amit ki age: 19")
print("Amit ki city: Pune")
print("---")
Example
# ─────────────────────────────────────
# GOOD CODE — Function use karo
# ─────────────────────────────────────
# ✅ Yeh karo
def print_student_info(name, age, city):
"""Student info print karta hai"""
print(f"{name} ki age: {age}")
print(f"{name} ki city: {city}")
print("---")
# Ab sirf ek baar function define karo
print_student_info("Rahul", 20, "Delhi")
print_student_info("Priya", 22, "Mumbai")
print_student_info("Amit", 19, "Pune")
| Rahul ki age | 20 |
| Rahul ki city | Delhi |
| Priya ki age | 22 |
| Priya ki city | Mumbai |
| Amit ki age | 19 |
| Amit ki city | Pune |
🏦 Real-World Example — Bank Account System
Example
# ─────────────────────────────────────
# Bank Account Functions
# ─────────────────────────────────────
def create_account(owner, initial_balance=0):
"""Naya bank account create karta hai"""
account = {
"owner": owner,
"balance": initial_balance,
"transactions": []
}
print(f"✅ Account created for: {owner}")
print(f"💰 Opening Balance: ₹{initial_balance}")
return account
def deposit(account, amount):
"""Account mein paisa deposit karna"""
if amount <= 0:
print("❌ Invalid amount! Amount positive hona chahiye.")
return account
account["balance"] += amount
account["transactions"].append(f"+₹{amount}")
print(f"✅ Deposited ₹{amount}")
print(f"💰 New Balance: ₹{account['balance']}")
return account
def withdraw(account, amount):
"""Account se paisa withdraw karna"""
if amount <= 0:
print("❌ Invalid amount!")
return account
if amount > account["balance"]:
print(f"❌ Insufficient balance! Current: ₹{account['balance']}")
return account
account["balance"] -= amount
account["transactions"].append(f"-₹{amount}")
print(f"✅ Withdrawn ₹{amount}")
print(f"💰 Remaining Balance: ₹{account['balance']}")
return account
def check_balance(account):
"""Balance check karna"""
print(f"\n🏦 Account Owner: {account['owner']}")
print(f"💰 Current Balance: ₹{account['balance']}")
print(f"📝 Transactions: {', '.join(account['transactions']) or 'None'}")
# ─── Demo ───────────────────────────
print("=" * 40)
print(" BANK ACCOUNT DEMO")
print("=" * 40)
acc = create_account("Sunita Sharma", 5000)
print()
deposit(acc, 2000)
print()
withdraw(acc, 1500)
print()
withdraw(acc, 10000) # Should fail
print()
check_balance(acc)
| ✅ Account created for | Sunita Sharma |
| 💰 Opening Balance | ₹5000 |
| 💰 New Balance | ₹7000 |
| 💰 Remaining Balance | ₹5500 |
| ❌ Insufficient balance! Current | ₹5500 |
| 🏦 Account Owner | Sunita Sharma |
| 💰 Current Balance | ₹5500 |
| 📝 Transactions | +₹2000, -₹1500 |
🔑 Function Naming Conventions
Example
# ─────────────────────────────────────
# Python naming conventions (PEP 8)
# ─────────────────────────────────────
# ✅ SAHI tarike
def calculate_total(): # snake_case
pass
def get_user_name(): # verb se shuru karo
pass
def is_valid_email(email): # boolean ke liye is/has/can
pass
def convert_to_uppercase(text): # descriptive naam
pass
# ❌ GALAT tarike
def CalculateTotal(): # PascalCase (classes ke liye hota hai)
pass
def ct(): # abbreviation — avoid karo
pass
def my_function_1(): # non-descriptive
pass
# ─── Private functions (underscore se shuru) ───
def _helper_function(): # internal use
pass
def __dunder_method(): # special methods (avoid manually)
pass
🔁 Multiple Return Values
Example
# ─────────────────────────────────────
# Function se multiple values return karna
# ─────────────────────────────────────
def get_circle_properties(radius):
"""
Circle ki properties return karta hai.
Returns:
tuple: (area, circumference, diameter)
"""
import math
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius
diameter = 2 * radius
return area, circumference, diameter # tuple return hota hai
# Unpack karo
r = 7
area, circ, diam = get_circle_properties(r)
print(f"Circle (radius = {r} cm):")
print(f" 📐 Area : {area:.2f} sq cm")
print(f" 🔵 Circumference : {circ:.2f} cm")
print(f" 📏 Diameter : {diam:.2f} cm")
| 📐 Area | 153.94 sq cm |
| 🔵 Circumference | 43.98 cm |
| 📏 Diameter | 14.00 cm |
⚡ Pass Statement in Functions
Example
# ─────────────────────────────────────
# pass — placeholder for empty function
# ─────────────────────────────────────
def future_feature():
"""Yeh function baad mein implement karenge"""
pass # SyntaxError nahi aayega
def todo_payment():
"""Payment processing — TODO"""
pass
# Abhi call kar sakte hain — koi error nahi
future_feature()
todo_payment()
print("Functions called successfully — no crash!")
Example
# OUTPUT:
Functions called successfully — no crash!
🧪 Functions ki Testing (Basic)
Example
# ─────────────────────────────────────
# Simple function testing
# ─────────────────────────────────────
def add(a, b):
"""Do numbers add karta hai"""
return a + b
def multiply(a, b):
"""Do numbers multiply karta hai"""
return a * b
def is_even(n):
"""Check karta hai ki number even hai ya nahi"""
return n % 2 == 0
# Tests
def run_tests():
print("🧪 Running Tests...")
print("-" * 30)
# Test 1
assert add(2, 3) == 5, "Add test failed!"
print("✅ add(2, 3) == 5 → PASS")
# Test 2
assert add(-1, 1) == 0, "Add negative test failed!"
print("✅ add(-1, 1) == 0 → PASS")
# Test 3
assert multiply(4, 5) == 20, "Multiply test failed!"
print("✅ multiply(4, 5) == 20 → PASS")
# Test 4
assert is_even(4) == True, "Even test failed!"
print("✅ is_even(4) == True → PASS")
# Test 5
assert is_even(7) == False, "Odd test failed!"
print("✅ is_even(7) == False → PASS")
print("-" * 30)
print("🎉 All tests passed!")
run_tests()
| ✅ add(2, 3) == 5 | PASS |
| ✅ add(-1, 1) == 0 | PASS |
| ✅ multiply(4, 5) == 20 | PASS |
| ✅ is_even(4) == True | PASS |
| ✅ is_even(7) == False | PASS |
❓ Interview Questions
Q1: Function aur Method mein kya fark hai?
Function — standalone hota hai, kisi class se linked nahi. Method — class ke andar define hota hai aur self parameter leta hai.python example
# Function
def greet(name):
return f"Hello, {name}!"
# Method (class ke andar)
class Person:
def greet(self): # self = method ki pehchaan
return "Hello!"Q2: Kya Python mein function ek variable mein store ho sakta hai?
python example
# Haan! Functions first-class objects hain Python mein
def square(x):
return x ** 2
my_func = square # Function ko variable mein store kiya
print(my_func(5)) # 25
print(type(my_func)) # <class 'function'>Q3: Empty function kaise define karte hain?
python example
def empty_function():
pass # pass statement use karo
# Ya phir ... (Ellipsis) bhi use kar sakte hain
def another_empty():
...Q4: Function ke andar function define ho sakta hai?
python example
def outer():
print("Outer function")
def inner(): # Nested function
print("Inner function")
inner() # Andar se call karo
outer()Code example
# OUTPUT:
Outer function
Inner functionQ5: Python mein function overloading hoti hai kya?
Nahi! Python mein traditional function overloading nahi hoti. Lekin *args aur default parameters se same effect achieve kar sakte hain.python example
def add(a, b=0, c=0):
return a + b + c
print(add(1)) # 1
print(add(1, 2)) # 3
print(add(1, 2, 3)) # 6📋 Summary
┌─────────────────────────────────────────────────────┐
│ FUNCTIONS BASICS — QUICK RECAP │
├─────────────────────────────────────────────────────┤
│ ✅ def keyword se function define karte hain │
│ ✅ () mein parameters likhte hain │
│ ✅ : ke baad indented body likhte hain │
│ ✅ return se value wapas dete hain │
│ ✅ Docstring se document karte hain │
│ ✅ DRY principle follow karte hain │
│ ✅ snake_case naming use karte hain │
│ ✅ Multiple values tuple mein return kar sakte hain│
│ ✅ pass se empty function banate hain │
└─────────────────────────────────────────────────────┘
🚀 Next Step: Function Arguments aur Parameters ke types seekhne ke liye function-arguments.mdx padhein!⚠️ Common Mistakes (Aam Galtiyan)
❌ Mistake 1: Function ko define karna lekin call nahi karna
python example
# GALAT — Function define kiya lekin call nahi kiya
def say_hello():
print("Hello World!")
# Kuch nahi hoga kyunki function call nahi huaCode example
# OUTPUT:
# (koi output nahi — function define hua lekin execute nahi hua)python example
# SAHI — Function call karna mat bhoolna!
def say_hello():
print("Hello World!")
say_hello() # ✅ Ab call kiyaExample
# OUTPUT:
Hello World!
❌ Mistake 2: Return aur Print mein confusion
python example
# GALAT — print use kiya return ki jagah
def add(a, b):
print(a + b) # sirf print karega, return nahi karega
result = add(3, 4) # result mein None store hoga!
print(f"Result: {result}")Example
# OUTPUT:
7
Result: None
python example
# SAHI — return use karo jab value wapas chahiye
def add(a, b):
return a + b # ✅ value return kiya
result = add(3, 4)
print(f"Result: {result}")Example
# OUTPUT:
Result: 7
❌ Mistake 3: Indentation galat karna
python example
# GALAT — IndentationError aayega
def greet():
print("Hello") # ❌ Indentation missing!
# SAHI
def greet():
print("Hello") # ✅ 4 spaces indent❌ Mistake 4: Parentheses () bhool jaana function call mein
python example
# GALAT — () ke bina function object reference milega
def get_message():
return "Namaste!"
print(get_message) # ❌ Function object print hoga
print(get_message()) # ✅ Function call hogaCode example
# OUTPUT:
<function get_message at 0x...>
Namaste!❌ Mistake 5: Function define hone se pehle call karna
python example
# GALAT — NameError aayega
# greet() # ❌ Abhi define nahi hua!
def greet():
print("Hello!")
greet() # ✅ Define hone ke baad call karoExample
# OUTPUT:
Hello!
❌ Mistake 6: Mutable default argument use karna
python example
# GALAT — list har call mein share hogi
def add_item_bad(item, items=[]): # ❌ Danger!
items.append(item)
return items
print(add_item_bad("apple"))
print(add_item_bad("banana")) # 😱 apple bhi aa gaya!Example
# OUTPUT:
['apple']
['apple', 'banana']
python example
# SAHI — None use karo default mein
def add_item_good(item, items=None): # ✅ Safe!
if items is None:
items = []
items.append(item)
return items
print(add_item_good("apple"))
print(add_item_good("banana")) # ✅ Correct!Example
# OUTPUT:
['apple']
['banana']
❌ Mistake 7: Return ke baad code likhna
python example
def calculate(a, b):
return a + b
print("Yeh kabhi execute nahi hoga!") # ❌ Dead code — unreachable
result = calculate(5, 3)
print(result)Example
# OUTPUT:
8
✅ Key Takeaways (Yaad Rakhne Wali Baatein)
- 🎯 Function ek reusable code block hai — ek baar likho, baar baar use karo. DRY principle follow karo!
- 🔑
defkeyword se function define hota hai aur()ke andar parameters likhte hain - 📤
returnstatement value wapas deta hai caller ko — agarreturnnahi likhoge tohNonemilega - 📝 Docstrings likhna best practice hai — triple quotes
"""mein function ka description likho - 🐍 snake_case naming convention use karo —
calculate_total()✅ notCalculateTotal()❌ - 🔄 Multiple values tuple ke form mein return kar sakte hain —
return a, b, c - 🏗️
passstatement empty function ka placeholder hai — baad mein implement karne ke liye - 📚 Built-in functions (
print(),len(),type()) Python already provide karta hai — pehle in mein check karo phir custom banao - 🧪 Testing karna important hai —
assertstatements se verify karo ki function sahi kaam kar raha hai - ⚡ Functions first-class objects hain Python mein — variable mein store, pass, aur return kar sakte hain
❓ FAQ (Frequently Asked Questions)
Q1: Function aur Method mein kya fark hai?
Function independently exist karta hai (def greet():) jabki Method kisi class/object se attached hota hai (obj.greet()). Method ka pehla parameterselfhota hai.
Q2: Kya ek function ke andar doosra function define kar sakte hain?
Haan! Isko nested function ya inner function kehte hain. Inner function sirf outer function ke andar accessible hota hai, bahar se call nahi kar sakte.
Q3: return aur print mein kya difference hai?
print()sirf screen pe output dikhata hai — value kahi store nahi hoti.returnvalue ko wapas bhejta hai caller ko — aap us value ko variable mein store kar sakte hain, calculations mein use kar sakte hain.
Q4: Agar function mein return nahi likhein toh kya hoga?
Python automaticallyNonereturn karega. Har function kuch na kuch return karta hai — agar explicitly nahi likha tohNonemilega.
Q5: Function ko kitne baar call kar sakte hain?
Unlimited baar! Yahi toh functions ka fayda hai — ek baar define karo, jitni baar chahein call karo. Har call independent hoti hai.
Q6: Kya function naam mein spaces allowed hain?
Nahi! Function naam mein spaces nahi aa sakte. Underscore_use karo words separate karne ke liye —calculate_total✅ notcalculate total❌
Q7: pass aur return None mein kya fark hai?
Functionally dono same hain — donoNonereturn karte hain. Lekinpasska intent hai "abhi kuch nahi karna, baad mein likhenge" jabkireturn Noneexplicitly keh raha hai "yeh function intentionally None return karta hai."
Q8: Python mein maximum kitne parameters ek function le sakta hai?
Technically koi hard limit nahi hai, lekin PEP 8 recommends 5-6 se zyada parameters avoid karo. Agar bahut zyada parameters hain toh dictionary ya class use karo.
🎯 Interview Questions (Detailed)
IQ1: Python mein def keyword ka kya role hai?
Answer:defkeyword Python ko batata hai ki aap ek function define kar rahe hain. Jab Pythondefdekhta hai, woh function object create karta hai aur usse given naam se bind karta hai. Function body tab tak execute nahi hoti jab tak function call nahi hota.
IQ2: First-class functions ka kya matlab hai Python mein?
Answer: Python mein functions first-class citizens hain — matlab: - Variable mein assign kar sakte hain:f = my_func- Function ke argument mein pass kar sakte hain:map(func, list)- Function se return kar sakte hain:return inner_func- Data structures (list, dict) mein store kar sakte hain
IQ3: Docstring aur Comment mein kya difference hai?
Answer: Comment (#) sirf developer ke liye hai — Python ignore karta hai. Docstring ("""...""") ek string object hai jo function ke__doc__attribute mein store hoti hai aur runtime pe accessible hoti hai viahelp()yafunc.__doc__. Docstring documentation ka standard tarika hai.
IQ4: Python mein function overloading kyun nahi hoti?
Answer: Python dynamically typed hai — same naam ka naya function purane ko overwrite kar deta hai. Lekin similar behavior achieve kar sakte hain via: - Default parameters:def add(a, b=0, c=0)-*argsaur**kwargs-functools.singledispatchdecorator
IQ5: return statement ke baad ka code execute hota hai kya?
Answer: Nahi! return statement function execution immediately terminate kar deta hai. Uske baad ka koi bhi code dead code hai aur kabhi execute nahi hoga. Yeh ek common mistake hai beginners ki.IQ6: Nested functions ka kya use case hai?
Answer: Nested functions (inner functions) use hote hain: - Closures banane ke liye (inner function outer variables remember karta hai) - Helper functions jo sirf parent function mein useful hain - Decorators implement karne ke liye - Data encapsulation — inner function bahar accessible nahi hota
IQ7: None return karna aur kuch return nahi karna — kya same hai?
Answer: Haan, functionally same hai. Agar function meinreturnstatement nahi hai, ya sirfreturnlikha hai bina value ke, yareturn Nonelikha hai — teeno cases mein caller koNonemilega. Lekin readability ke liye explicitreturn Nonelikhna better hai agar function ka intent value return karna hai lekin kisi condition mein nahi kar paa raha.
IQ8: Python mein function call karne pe internally kya hota hai?
Answer: Jab function call hota hai: 1. New frame create hota hai call stack pe 2. Arguments evaluate hote hain aur parameters mein bind hote hain 3. Function body execute hoti hai naye frame mein 4. Return value caller ko milti hai 5. Frame destroy hota hai aur stack se pop hota hai Yeh pura process call stack mechanism kehlata hai.
IQ9: *args aur **kwargs ka basic concept kya hai?
Answer:*argsfunction ko variable number of positional arguments accept karne deta hai (tuple mein store hote hain).kwargsvariable number of keyword arguments** accept karne deta hai (dictionary mein store hote hain). Yeh function ko flexible banate hain — caller kitne bhi arguments pass kar sakta hai.
IQ10: Function ko memory efficient kaise banayein?
Answer: - Generator functions use karo (yield) large data ke liye - Mutable default arguments avoid karo (memory leak ho sakti hai) - Local variables prefer karo global se — local faster hote hain - Early return pattern use karo — unnecessary computation avoid hogi - Function ke andar unnecessary copies mat banao (slicing se naya list banta hai)🚀 Next Step: Function Arguments aur Parameters ke types seekhne ke liye function-arguments.mdx padhein!Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Functions Basics in Python.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, functions, basics, functions basics in python
Related Python Master Course Topics
Continue learning this concept
FunctionsDecorators in PythonDetailed guide to Python decorators — function decorators, class decorators, stacking, functools.wraps, and real-world use cases. Learn with examples and best practices.FunctionsFunction Arguments in PythonComplete guide to Python function arguments — positional, keyword, default, *args, **kwargs and their real-world use cases. Understand argument types with best practices.FunctionsGenerators in PythonPython generators ki detailed guide — yield keyword, generator functions, generator expressions, send/throw/close, aur real-world use cases jaise infinite sequences, data pipelines, aur memory-efficient file processing. Hindi mein.FunctionsLambda Functions in PythonComplete guide to Python lambda functions — syntax, use cases, usage with map/filter/sorted, and comparison with regular functions. Learn with practical examples.FunctionsRecursive Functions in PythonPython mein recursion ki complete guide — base case, recursive case, call stack, fibonacci, factorial, binary search aur tree traversal ke saath Hindi explanations.FunctionsReturn Statement in PythonPython mein return statement ki poori guide — single/multiple return values, early return, None return, aur real-world patterns. Hindi mein samjho return ke saare use cases.