📘 अध्याय 1: फ़ंक्शन क्या है? (What is Function in Python in Hindi)
Table of Contents
Toggle📖 परिभाषा (Definition)
Python में फ़ंक्शन (Function) एक reusable block of code है जो किसी विशेष कार्य (task) को पूरा करने के लिए लिखा जाता है। एक बार function बना लेने के बाद हम इसे बार-बार call कर सकते हैं, जिससे time बचता है, code readable और structured रहता है।
Real-life Analogy
सोचिए आपके पास एक Calculator है। उसमें multiply (×) बटन दबाते ही multiplication का काम हो जाता है। यही multiply बटन Python में एक function जैसा है — एक predefined काम जो हर बार इस्तेमाल करने पर वही result देगा।
⚙️ Syntax (Python Function Syntax)
def function_name(parameters): # Code Block return result
➡️ यहाँ def keyword function बनाने के लिए प्रयोग होता है। ➡️ function का नाम meaningful होना चाहिए। ➡️ parameters optional होते हैं। ➡️ return statement result वापस देता है।
📝 Example: Python में पहला Function
def greet(): print("नमस्ते, Vista Academy में आपका स्वागत है!") greet()
👉 ऊपर दिए गए function का नाम greet() है।
👉 जब हम greet()
को call करते हैं, यह “नमस्ते, Vista Academy में आपका स्वागत है!” print करता है।
यह सबसे simple example है कि Python में function कैसे काम करता है।
💡 नोट: Python Function in Hindi सीखने का सबसे अच्छा तरीका है छोटे-छोटे programs बनाना और उन्हें बार-बार run करना।
🛠️ अध्याय 2: Function Basics — Parameters, Return, Default & Keyword Arguments (सहज समझ)
इस अध्याय में हम सीखेंगे कि functions में **arguments (input)** कैसे पास करते हैं, **return value** क्या होती है, और **default / keyword arguments** का उपयोग कैसे करें। छोटे उदाहरणों से step-by-step समझाया गया है ताकि आप तुरंत practice कर सकें।
📥 Parameters और Arguments क्या हैं?
Parameter वह नाम है जो function definition में दिए जाते हैं (placeholder)। Argument वह actual value है जो function call के समय दी जाती है।
# Parameters: a, b (definition में) def add(a, b): return a + b # Arguments: 5, 7 (call में) print(add(5, 7)) # Output: 12
🔁 return क्या करती है?
`return` statement function को एक value वापस भेजने के लिए होता है। अगर `return` नहीं होगा तो function `None` लौटाएगा (जब print या variable में store किया जाए)।
def multiply(a, b): return a * b res = multiply(4, 5) print(res) # Output: 20
नोट: कई बार function सिर्फ side-effect (जैसे print करना, database लिखना) करता है — ऐसे functions explicit `return` नहीं भी कर सकते।
🆚 Function — With Return vs Without Return (अंतर सरल शब्दों में)
def square(n): return n*n print(square(6)) # 36
Value को reuse करने लायक बनाता है — variable में store कर सकते हैं।
def greet(name): print("Hello", name) greet("Asha") # prints Hello Asha
Side-effect (print) करता है; value reuse नहीं कर सकते।
🎯 Default Parameters (Default Values)
जब कोई argument call में ना दिया जाए तो default parameter value use होती है। इससे functions और flexible बनते हैं।
def greet(name="Student"): print("नमस्ते", name) greet() # नमस्ते Student greet("Yogesh") # नमस्ते Yogesh
🔖 Keyword Arguments (नाम के साथ arguments)
Arguments को नाम के साथ देने पर order का ध्यान नहीं रखना पड़ता। यह readability बढ़ाता है।
def student(name, age, course): print(name, age, course) student(age=22, course="Python", name="Radha") # Output: Radha 22 Python
✨ Arbitrary Arguments — *args & **kwargs
कभी नहीं पता कि कितने values आएँगे — ऐसे में `*args` (tuple) और `**kwargs` (dict) उपयोगी होते हैं।
def info(name, *scores, **details): print("Name:", name) print("Scores:", scores) print("Details:", details) info("Aman", 78, 82, 91, city="Delhi", course="Analytics")
➤ `scores` एक tuple बन जाएगा। ➤ `details` एक dict बन जाएगा — keys & values के साथ।
🧩 छोटा अभ्यास (Practice)
- एक function लिखें
is_even(n)
जो बताये कि संख्या even है या नहीं — boolean return करें। - एक function लिखें
avg(*nums)
जो दिए गए numbers का average दे। - `greet` function को modify करें ताकि default name `”Student”` हो और यदि कुछ दिया जाए तो उस नाम से greet करे।
(Solution try करें और console में run कर के देखें — practice से ही mastery आती है!)
💡 SEO Tip: इस सेक्शन में natural language में keywords जैसे function in python in hindi और what is function in python in hindi का उपयोग किया गया है। छोटे code examples और practice problems पढ़ने वालों को रुचि बनाए रखते हैं और dwell time बढ़ाते हैं — जो SEO के लिए अच्छा है।
🌍 अध्याय 3: Scope in Functions — Local, Global और Keywords की समझ
Python में scope का मतलब है कि कोई variable कहाँ तक accessible है। अगर आप function के अंदर variable बनाते हैं तो वो बाहर access नहीं होगा। इसी तरह global variable पूरे program में available रहता है। इस concept को समझना बहुत ज़रूरी है क्योंकि गलत scope की वजह से अक्सर NameError या गलत output मिलता है।
📍 Local Variables
Function के अंदर बनाया गया variable सिर्फ उसी function में accessible होता है। इसे local variable कहते हैं।
def my_func(): x = 10 # Local variable print("Inside function:", x) my_func() print("Outside function:", x) # Error: x is not defined
👉 यहाँ x
सिर्फ function के अंदर काम करेगा। बाहर print करने पर error मिलेगा।
🌐 Global Variables
Global variable पूरे program में access किया जा सकता है, function के अंदर भी (लेकिन modify करने के लिए global
keyword चाहिए)।
x = 50 # Global variable def show(): print("Inside function:", x) show() print("Outside function:", x)
👉 यहाँ x
function के अंदर और बाहर दोनों जगह access किया जा सकता है।
📝 global Keyword
अगर function के अंदर global variable को बदलना हो तो global
keyword का प्रयोग करना पड़ता है।
x = 10 def update(): global x x = x + 5 print("Inside function:", x) update() print("Outside function:", x)
👉 यहाँ x
को function के अंदर modify किया गया और वो बाहर भी reflect हुआ।
🔄 nonlocal Keyword
Nested function में inner function, outer function के variable को modify करने के लिए nonlocal
का प्रयोग करता है।
def outer(): x = 5 def inner(): nonlocal x x = x + 10 print("Inner:", x) inner() print("Outer:", x) outer()
👉 यहाँ nonlocal
ने outer function के variable x
को modify किया।
✅ Best Practices (Scope के लिए सुझाव)
- Local variables का use ज़्यादा करें — इससे bugs कम होंगे।
- Global variables avoid करें, जब तक बहुत ज़रूरी न हो।
global
औरnonlocal
का उपयोग केवल समझदारी से करें।- Variable naming clear रखें ताकि scope-related confusion न हो।
🧩 छोटा अभ्यास (Practice)
- एक function बनाएँ जो local variable use करे और बाहर access करने पर error दे।
- Global variable
counter
को हर बार function call पर 1 से बढ़ाएँ। - एक nested function बनाएँ जो
nonlocal
keyword से outer variable को update करे।
🔍 अध्याय 4: Types of Functions — Built-in, User-defined, Recursive, Lambda & Higher-Order
Python में कई तरह के functions होते हैं — कुछ पहले से बने (built-in), कुछ हम खुद बनाते हैं (user-defined), कुछ recursive तरीके से खुद को call करते हैं, और कुछ एक-line anonymous functions होते हैं (lambda)। साथ में higher-order functions जैसे map
, filter
, और reduce
डेटा pipelines बनाने में बहुत काम आते हैं।
🧩 Built-in Functions (पहले से उपलब्ध)
Python में बहुत सारे built-in functions होते हैं — जैसे len()
, max()
, sum()
, print()
आदि। ये तुरंत उपयोग के लिए तैयार आते हैं।
items = [10, 5, 20] print("Length:", len(items)) # 3 print("Max:", max(items)) # 20 print("Sum:", sum(items)) # 35
✍️ User-defined Functions (हमारे बनाए हुए)
आप अपनी logic के अनुसार functions define करते हैं — जिससे code modular और reusable बनता है।
def greet(name): return f"नमस्ते, {name}!" print(greet("Sonal")) # नमस्ते, Sonal!
🔁 Recursive Functions (पुनरावर्ती फ़ंक्शन)
Recursive function वह function है जो अपने आप को ही call करता है। अक्सर factorial या fibonacci जैसे problems में उपयोग होता है। ध्यान रखें कि base case आवश्यक है वरना infinite recursion हो सकती है।
def factorial(n): if n == 0: return 1 # base case return n * factorial(n-1) print(factorial(5)) # 120
def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2) print(fib(7)) # 13
🔔 Note: Fibonacci के लिए recursion simple है पर inefficient हो सकता है — large n के लिए memoization या iterative approach बेहतर है।
λ Lambda Functions (Anonymous / One-line)
Lambda functions छोटे, anonymous functions होते हैं — अक्सर तब उपयोग होते हैं जब function को temporary तरीके से चाहिए।
# lambda for square square = lambda x: x*x print(square(6)) # 36 # inline use with sorted pairs = [(1, 'a'), (3, 'c'), (2, 'b')] print(sorted(pairs, key=lambda x: x[0])) # sorted by first element
🔗 Higher-Order Functions — map, filter, reduce
Higher-order functions वे functions हैं जो दूसरे functions को argument के रूप में लेते हैं या function return करते हैं। Python में सामान्य examples हैं map
, filter
, और reduce
(reduce के लिए functools
import करना पड़ता है)।
nums = [1,2,3,4] squared = list(map(lambda x: x*x, nums)) print(squared) # [1,4,9,16]
nums = [1,2,3,4,5,6] evens = list(filter(lambda x: x%2==0, nums)) print(evens) # [2,4,6]
from functools import reduce nums = [1,2,3,4] product = reduce(lambda a,b: a*b, nums) print(product) # 24
🧭 कब कौन सा उपयोग करें?
- Built-in: जब standard operation चाहिए (len, sum)।
- User-defined: custom logic के लिए — readability और reuse के लिए।
- Recursive: जब समस्या को छोटे sub-problems से हल करना आसान हो (पर performance ध्यान दें)।
- Lambda + map/filter: छोटे data transformations के लिए compact और readable।
🧩 अभ्यास (Practice)
- एक user-defined function लिखें जो किसी सूची के सभी odd numbers को filter करके return करे (use filter / list comprehension)।
- Lambda और map का उपयोग करके किसी संख्या सूची के सभी elements को तीन गुना करें।
- Recursive approach से palindrome check function लिखने की कोशिश करें (hint: string slicing)।
💡 SEO Tip: इस chapter में तरह-तरह के functions और उनके उपयोग के उदाहरण दिए गए हैं — ऐसे rich technical details Google और readers दोनों को पसंद आते हैं। कीवर्ड्स जैसे function in python in hindi और types of functions in python in hindi को natural तरीके से शामिल किया गया है।
🎯 अध्याय 5: Function Arguments in Depth — Positional, Keyword, *args & **kwargs (आसान भाषा में)
इस अध्याय में हम गहराई से समझेंगे कि Python functions में arguments कैसे पास किए जाते हैं — positional, keyword, default, *args और **kwargs। Practical examples से समझना आसान होगा और ये Data Analytics scripts में बहुत काम आते हैं।
1️⃣ Positional Arguments (क्रम से पास किए जाने वाले)
Positional arguments में values function के parameters की defined order के अनुसार भेजी जाती हैं।
def area(length, width): return length * width print(area(5, 3)) # 15 (length=5, width=3)
अगर order बदलें तो गलत result आ सकता है — इसलिए order का ध्यान रखें।
2️⃣ Keyword Arguments (नाम के साथ)
Keyword arguments में आप parameter-name = value लिखकर भेजते हैं — इससे order matter नहीं करता और code readable बनता है।
def book_info(title, author, year): print(title, author, year) book_info(author="Arun", title="Python Sikhe", year=2024)
Keyword arguments beginners के लिए safe और readable तरीका है।
3️⃣ Default Arguments (डिफ़ॉल्ट वैल्यू)
अगर function call में कुछ arguments न दिए जाएँ तो default values उपयोग होती हैं। ध्यान रखें कि default parameters को non-default के बाद ही रखें।
def connect(host, port=3306): print("Connecting to", host, "on", port) connect("localhost") # port = 3306 connect("db.server.com", 5432) # port overridden
Tip: Default values immutable (जैसे int, str) रखें; mutable defaults like list/dict से सावधान रहें — unexpected behavior हो सकता है।
4️⃣ *args — Arbitrary Positional Arguments
जब हमें unknown number of positional values चाहिए हों — `*args` उन्हें एक tuple में capture कर लेता है।
def sum_all(*nums): total = 0 for n in nums: total += n return total print(sum_all(2,3,5)) # 10 print(sum_all(1,2,3,4)) # 10
`*args` का नाम conventionally `args` ही रखा जाता है पर कोई भी नाम चल जाएगा — important हिस्सा `*` है।
5️⃣ **kwargs — Arbitrary Keyword Arguments
जब unknown number of named arguments चाहिए हों — `**kwargs` उन्हें एक dictionary में capture कर लेता है।
def profile(name, **info): print("Name:", name) for k,v in info.items(): print(k, ":", v) profile("Mira", age=23, city="Dehradun", course="Analytics")
`**kwargs` flexible APIs बनाते हैं — libraries और toolkits में अक्सर यही pattern उपयोग होता है।
6️⃣ Mixing — Order Rules
Argument types को mix करते समय syntax order का पालन करें: positional, *args, default/keyword, **kwargs — वरना SyntaxError आ सकती है।
def example(a, b=5, *args, **kwargs): print(a, b, args, kwargs) example(1, 2, 3, 4, x=10, y=20) # Output: 1 2 (3,4) {'x':10, 'y':20}
⚠️ Mutable Default Argument Trap (सावधान)
अगर default argument mutable object (list/dict) हो तो function calls के बीच वह object shared रहेगा — unexpected behavior। इसे avoid करने के लिए `None` use करें और फिर अंदर new object बनाएं।
# गलत तरीका def add_item(item, lst=[]): lst.append(item) return lst print(add_item(1)) # [1] print(add_item(2)) # [1, 2] <-- shared list! # सही तरीका def add_item(item, lst=None): if lst is None: lst = [] lst.append(item) return lst
🧩 अभ्यास (Practice)
- एक function `concat(*parts)` लिखें जो किसी भी number की strings को जोड़कर लौटाए।
- `make_url(base, **params)` लिखें — यह base URL के बाद params को query string के रूप में जोड़कर return करे।
- Mutable default trap का एक और example बनाकर समझाएँ कि क्यों problem आती है।
💡 SEO Tip: इस chapter में natural Hindi explanations के साथ keywords जैसे function in python in hindi, *args in python in hindi, और **kwargs in hindi शामिल किये गए हैं — जिससे search visibility बढ़ने में मदद मिलेगी।
🧭 अध्याय 6: Documentation & Best Practices — साफ़, maintainable और परखा हुआ Code
अच्छे functions सिर्फ सही output नहीं देते — वे पढ़ने, समझने और maintain करने में आसान होने चाहिए। इस अध्याय में हम naming conventions, docstrings, type hints, side-effects से बचने और modular design की best practices सीखेंगे।
🔤 Function Naming Conventions (नामकरण)
Python की PEP8 style guide के अनुसार function names छोटे, lowercase और words को underscore से अलग करें — जैसे calculate_total
, get_user_input
। नाम meaningful रखें ताकि किसी को code पढ़कर function का मकसद समझ आ जाए।
# अच्छा def calculate_average(scores): ... # खराब def calc(sc): ...
📚 Docstrings — Documentation in Code
हर function के ऊपर docstring लिखें जो बताये कि function क्या करता है, parameters क्या हैं, और क्या return करता है। इससे IDE hints, auto-doc generation, और टीम collaboration आसान हो जाता है।
def greet(name: str) -> str: """ Greet the user with their name. Parameters: name (str): The name of the user. Returns: str: Greeting message. """ return f"नमस्ते, {name}!"
Tip: Docstrings के लिए Google-style या NumPy-style formats उपयोगी होते हैं — consistent रखें।
🔎 Type Hinting (Type Annotations)
Type hints से code पढ़ने में मदद मिलती है और static checkers (mypy) से bugs जल्दी मिल जाते हैं। Python में यह optional है पर बड़े projects में बहुत उपयोगी होता है।
def add(a: int, b: int) -> int: return a + b from typing import List def avg(values: List[float]) -> float: return sum(values) / len(values)
⚖️ Avoid Side Effects — Pure Functions
जहाँ संभव हो, functions को pure रखें — यानी वे केवल input लेते हैं और output देते हैं, बाहरी state को नहीं बदलते। इससे testing आसान और bugs कम होते हैं।
# impure (side effect) count = 0 def increment(): global count count += 1 # pure def increment_val(x): return x + 1
Note: कुछ functions side-effects करेंगे (logging, writing files)। इन्हें स्पष्ट रखें और document करें।
🧩 Modularization — छोटे, single-responsibility functions
हर function का एक ही काम होना चाहिए (Single Responsibility Principle)। छोटे functions combine करके बड़े काम आसान बन सकते हैं। Modules (.py files) में related functions को group करें।
# utils.py def read_csv(path): ... def clean_data(df): ... # main.py from utils import read_csv, clean_data
🧪 Unit Testing & Type Checking
छोटे functions को unit tests से कवर करें — pytest या unittest उपयोगी हैं। Type checking के लिए mypy चलाएँ। CI pipelines में tests जोड़ें ताकि हर commit पर code verified रहे।
# test_utils.py (pytest) from utils import add def test_add(): assert add(2,3) == 5
⚡ Performance Tips
- Heavy computations को function में रखें और optimize करें (vectorized ops for pandas/numpy)।
- Immutable objects prefer करें जहाँ संभव हो।
- Recursive solutions के लिए memoization consider करें या iterative approach लें।
📝 छोटे-से Checklist (Publish-ready functions)
- Meaningful name + docstring
- Type hints where helpful
- Avoid unexpected side-effects
- Unit tests for edge cases
- Keep functions short (max ~30 lines ideally)
🧩 अभ्यास (Practice)
- किसी function के लिए अच्छे docstring लिखें (Google-style)।
- एक impure function को pure version में बदलने की कोशिश करें।
- एक छोटा pytest test लिखकर run करें (example ऊपर देखें)।
💡 SEO Tip: Chapter में practical tips और code hygiene जैसे topics add करने से experienced readers भी रुचि लेंगे — इससे backlink और engagement दोनों बढ़ने की संभावना रहती है। कीवर्ड्स जैसे function in python in hindi, docstring in python hindi, और python best practices in hindi शामिल किए गए हैं।
🚀 अध्याय 7: Advanced Functions — Nested, Closures, Decorators और Recursion Practicals
अब हम functions के advanced concepts सीखेंगे जो real-world Python development और Data Analytics pipelines में बहुत काम आते हैं — जैसे nested functions, closures, decorators और recursion के power-uses। सरल उदाहरणों से concept clear करेंगे।
📦 Nested Functions (Function के अंदर function)
Nested function वह होता है जो किसी outer function के अंदर define किया जाए। यह encapsulation और scope control के लिए उपयोगी है।
def outer(name): def inner(): print("Hello", name) inner() outer("Ravi") # Hello Ravi
👉 Inner function बाहर से directly accessible नहीं होगा — यह outer के context को इस्तेमाल कर सकता है।
🔒 Closures — Function के साथ State को बाँधना
Closure तब बनता है जब inner function अपने enclosing scope के variables को याद रखता है — भले ही outer function का execution खत्म हो चुका हो। यह छोटे stateful functions बनाने में उपयोगी है।
def make_multiplier(n): def multiplier(x): return x * n return multiplier times3 = make_multiplier(3) print(times3(5)) # 15
👉 `make_multiplier(3)` ने एक closure लौटाया जिसमें `n=3` bound है। यह pattern decorators और functional programming में बहुत उपयोगी है।
🔧 Practical: Simple Counter using Closure
def make_counter(): count = 0 def increment(): nonlocal count count += 1 return count return increment c = make_counter() print(c()) # 1 print(c()) # 2
👉 `count` closure में preserved रहता है — यह small stateful API जैसा व्यवहार देता है।
🎀 Decorators — Functions को wrap करके नया व्यवहार जोड़ना
Decorator एक function है जो दूसरी function को modify या extend करता है बिना उसके source को बदले। Python में यह `@decorator` syntax से प्रयोग होता है।
def debug(func): def wrapper(*args, **kwargs): print("Calling:", func.__name__) result = func(*args, **kwargs) print("Returned:", result) return result return wrapper @debug def add(a, b): return a + b print(add(3,4)) # Output: # Calling: add # Returned: 7 # 7
👉 Decorators logging, timing, authentication, caching जैसे patterns implement करने के लिए बढ़िया हैं।
✨ Decorator with Parameters
def repeat(times): def decorator(func): def wrapper(*args, **kwargs): for _ in range(times): func(*args, **kwargs) return wrapper return decorator @repeat(3) def say_hi(): print("Hi!") say_hi() # prints "Hi!" three times
👉 यहाँ `repeat(3)` ने एक decorator बनाया जो function को multiple times run करता है।
🔁 Recursion Practicals — Advanced Use-cases
Recursion powerful है पर समझदारी से use करनी चाहिए। नीचे कुछ practical examples हैं जिनसे आप advanced recursion patterns समझ पाएँगे।
def recursive_sum(arr): if not arr: return 0 return arr[0] + recursive_sum(arr[1:]) print(recursive_sum([1,2,3,4])) # 10
def subsets(nums): res = [] def backtrack(i, path): if i == len(nums): res.append(path[:]) return # don't include nums[i] backtrack(i+1, path) # include nums[i] path.append(nums[i]) backtrack(i+1, path) path.pop() backtrack(0, []) return res print(subsets([1,2])) # [[], [2], [1], [1,2]]
🔔 Tip: Backtracking and divide-&-conquer algorithms commonly use recursion; practice small problems to build intuition।
🧭 कब किस pattern का उपयोग करें?
- Nested functions & closures: state encapsulation और small factories बनाते समय।
- Decorators: logging, authorization, caching और code reuse के लिए (cross-cutting concerns)।
- Recursion: tree traversal, combinatorics, backtracking—पर performance के लिए memoize करें।
🧩 अभ्यास (Practice)
- Closure का use करके एक `power(n)` function बनाइए जो किसी number का n-th power दे (उदा. power(3)(2) → 8)।
- Decorator लिखिए जो किसी function के execution time को print करे (use `time.time()`)।
- Recursive तरीके से binary search implement कीजिये और iterative version से compare कीजिए।
💡 SEO Tip: Advanced topics जैसे closures in python in hindi, decorator in python hindi, और recursive functions in hindi को clear examples के साथ शामिल करने से आपका ब्लॉग both beginners और advanced readers को attract करेगा — जिससे engagement और authority बढ़ेगी।
📊 अध्याय 8: Data Analytics में Functions का उपयोग — Pandas, Cleaning & Practical Examples
Data Analytics में functions का प्रयोग अक्सर data cleaning, transformation और feature engineering के लिए किया जाता है। इस अध्याय में हम देखेंगे कि कैसे छोटे, reusable functions pandas pipelines में लगाकर साफ़ और fast data workflows बनाये जा सकते हैं।
🔎 क्यों Functions जरूरी हैं — Reuse, Readability और Reproducibility
- एक ही cleaning logic कई datasets पर reuse कर सकते हैं।
- Readable pipelines बनते हैं — हर step का नाम और काम स्पष्ट रहता है।
- Testing आसान हो जाती है — small functions को unit test करें।
🧹 Example 1 — Data Cleaning Function (Strip, Lower, NaN handling)
छोटे functions बनाकर text columns को clean करें — strip, lower-case और empty-to-NaN कर के।
import pandas as pd import numpy as np def clean_text(x): if pd.isna(x): return np.nan x = str(x).strip() if x == "": return np.nan return x.lower() df = pd.DataFrame({"name":[" Asha ", " ", None, "Ravi"]}) df["name_clean"] = df["name"].apply(clean_text) print(df)
👉 `clean_text` छोटे-छोटे steps को एक reusable function में बाँट देता है — testing और reuse आसान।
⚡ Vectorized operations vs apply()
Pandas में जहाँ संभव हो vectorized operations (built-in methods) प्रयोग करें — वे Python-level loops से बहुत तेज़ होते हैं। `apply()` उपयोगी है जब complex logic per-row चाहिए।
# vectorized (fast) df["full_name"] = df["first"] + " " + df["last"] # apply (slower) df["full_name"] = df.apply(lambda r: r["first"] + " " + r["last"], axis=1)
Tip: जब thousands/millions rows हों तो vectorized approach प्राथमिकता दें।
💱 Example 2 — Currency Conversion (USD → INR) — Reusable function
Exchange rate को function में रखें ताकि बार-बार update कर सकें और same function pipeline में apply कर सकें।
RATE_USD_INR = 83.25 def usd_to_inr(usd, rate=RATE_USD_INR): if pd.isna(usd): return np.nan return round(usd * rate, 2) df = pd.DataFrame({"USD":[1, 10, None, 25.5]}) df["INR"] = df["USD"].apply(usd_to_inr) print(df)
👉 Rate को central constant में रखें या config file में रखें — audit और reproducibility बेहतर रहता है।
📈 Example 3 — groupby + custom aggregation function
अपने custom aggregation logic को function में रखें और फिर `groupby().agg()` में refer करें — readable और testable रहता है।
def pct_non_null(series): return series.notna().sum() / len(series) * 100 df = pd.DataFrame({ "city":["A","A","B","B"], "sales":[100, None, 50, 70] }) agg = df.groupby("city").agg({ "sales": ["sum", pct_non_null] }) print(agg)
👉 Custom function का नाम descriptive रखें — reporting में clarity आती है।
🧠 Example 4 — Feature Engineering function
Feature creation को functions में रखकर repeatable pipelines बनाएं — Model building में helpful।
def compute_income_per_person(row): if row["household_size"] == 0 or pd.isna(row["household_size"]): return np.nan return row["household_income"] / row["household_size"] df["income_per_person"] = df.apply(compute_income_per_person, axis=1)
👉 `apply(axis=1)` heavy होता है — पर कभी-कभी row-wise logic के लिए आवश्यक है। जहाँ possible vectorize करें।
🔁 Pipelines — Smaller Functions chained together
छोटे functions बनाएं और उन्हें pipeline में stitch करें — इससे step-by-step reproducible workflow बनता है।
def load(path): ... def clean(df): ... def feature_engineer(df): ... def save(df, path): ... df = load("data.csv") df = clean(df) df = feature_engineer(df) save(df, "processed.csv")
Tip: हर function का input और output clearly document करें — यही reproducibility की नींव है।
⚡ Performance Tips (Big Data में ध्यान रखें)
- Vectorized ops (pandas/numpy) > apply() > pure-Python loops.
- Chunking: बड़े CSV पर chunk-wise processing करें (`pd.read_csv(…, chunksize=…)`).
- Use `numba`/`cython`/`polars` जब performance critical हो।
- Memoize expensive functions अगर same inputs बार-बार आते हों (`functools.lru_cache`).
🧩 अभ्यास (Practice)
- एक function लिखिए `clean_dates(col)` जो अलग-अलग date formats को pandas datetime में convert करे।
- एक pipeline बनाइए: load → clean_text_columns → convert_numeric → save। हर step एक function हो।
- `groupby` के बाद custom top-n function लिखिए जो हर group का top-2 sales rows लौटाए।
💡 SEO Tip: Data Analytics examples और pandas code snippets शामिल करने से आपका ब्लॉग practical search intent (जैसे “pandas apply example in hindi”, “data cleaning in python hindi”) को serve करेगा — जिससे organic traffic बढ़ने की संभावना रहती है।
🔟 Python Function के Practical Examples (With Output)
नीचे दिए गए 10 उदाहरण आपको Function को real-world में use करने का तरीका समझाते हैं। हर उदाहरण कॉपी-पेस्ट करने योग्य है — और Output भी दिया गया है।
1️⃣ Hello Function
📤 Output: Hello World!
2️⃣ Sum of Two Numbers
📤 Output: 7
3️⃣ Odd or Even
📤 Output: Odd
4️⃣ Factorial
📤 Output: 120
5️⃣ Reverse String
📤 Output: nohtyP
6️⃣ Maximum of 3 Numbers
📤 Output: 12
7️⃣ Count Vowels
📤 Output: 2
8️⃣ Is Prime Number?
📤 Output: True
9️⃣ Power Function
📤 Output: 8
🔟 Greeting with Name
📤 Output: Hello Ravi
❓ अक्सर पूछे जाने वाले सवाल — Python Functions
नीचे दिए गए सरल और साफ़ जवाब आपके concepts को और ज़्यादा स्पष्ट करेंगे — quick-reference के लिए उपयुक्त।
👉 Python में Function क्या होता है?
👉 Parameters और Arguments में क्या फर्क है?
def f(x):
→ x
parameter; f(5)
→ 5
argument।
👉 क्या एक function में loop use किया जा सकता है?
👉 क्या एक function multiple values return कर सकता है?
return a, b
— call करने पर आप x,y = func()
से unpack कर सकते हैं।
👉 क्या Python में function के अंदर दूसरा function define किया जा सकता है?
1️⃣ Capstone Project — Unit Converter & Utility CLI
यह प्रोजेक्ट आपके function skills और modular code writing को मजबूत करेगा। इसमें temperature, distance और currency conversion के लिए छोटे-छोटे functions बनाएंगे।
🔹 उद्देश्य
- Functions को reusable बनाना
- CLI से user input लेना
- Invalid inputs handle करना
📝 Code Snippet (in-place)
# converters.py def c_to_f(c): return (c * 9/5) + 32 def f_to_c(f): return (f - 32) * 5/9 def ft_to_cm(ft): return ft * 30.48 def km_to_m(km): return km * 1000 RATE_USD_INR = 83.25 def usd_to_inr(usd, rate=RATE_USD_INR): return round(usd * rate, 2)
📦 Deliverables
- `converters.py` module (functions with docstrings)
- `cli.py` script (user prompts/argparse)
- README with usage examples
✅ Evaluation Rubric (10)
- Functions modularity — 3
- Correctness & edge-cases — 3
- CLI usability — 2
- Code style — 2
🚀 Data Science या Data Analytics – सीखें Real Projects के साथ!
अब समय है अपने Skill को Next Level पर ले जाने का। Vista Academy आपको देता है 100% Practical सीखने का मौका – वो भी बिल्कुल शुरुआत से, Real-World Projects के साथ।
📞 संपर्क करें: 9411778145 | 📍 Vista Academy, Dehradun
📝 Python Functions — MCQ Quiz
प्रति प्रश्न आगे ➜ बटन से आगे बढ़ें — उत्तर अंत में दिए हैं। (No JavaScript)
Ready? Start Quiz
कुल 15 प्रश्न — एक-एक करके आगे बढ़ें। उत्तर अंत में दिए गए हैं।
1) Python में function define करने के लिए कौन सा keyword use होता है?
2) Function को call करने का सही तरीका क्या है?
3) Function में pass किए गए values को क्या कहते हैं?
4) Function में define किए गए नाम (x,y) कहलाते हैं?
5) Python में value लौटाने के लिए कौन सा keyword use होता है?
6) अगर function में return statement न हो तो by default क्या लौटता है?
7) Python में function inside function को क्या कहते हैं?
8) Anonymous functions को Python में क्या कहते हैं?
9) Function arguments में default value देने का syntax क्या है?
10) Function के अंदर global variable को बदलने के लिए कौन सा keyword जरूरी है?
11) Function का फायदा क्या है?
12) Function call करते समय values pass करने के तरीके?
13) Python में कितने values return की जा सकती हैं?
14) Function docstring define करने के लिए क्या use होता है?
15) कौन सा decorator class method बनाने के लिए use होता है?
✅ Answers — Python Functions Quiz
(प्रत्येक प्रश्न के सही उत्तर नीचे दिए गए हैं — उपयोगकर्ता अपना स्कोर खुद देख सकता है)
1) def 2) myfunc() 3) Arguments 4) Parameters 5) return 6) None 7) Nested function 8) lambda 9) def f(x=5): 10) global 11) सभी 12) सभी 13) असीमित (tuple/list में) 14) """triple quotes""" 15) @classmethod