Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟡 Advanced Python  ·  Lesson 30

Python Best Practices

साफ़ code क्यों ज़रूरी है

Code लिखे जाने से कहीं ज़्यादा पढ़ा जाता है – साथियों द्वारा, interviewers द्वारा, और छह महीने बाद ख़ुद आपके द्वारा। साफ़ code में bugs कम होते हैं, बदलना आसान होता है और GitHub portfolio तथा machine-coding rounds में अच्छी छाप छोड़ता है।

पहले और बाद: एक program, दो style

Python – before.py (works, but…)
import json
def f(d,t=[]):
    for i in range(len(d)):
        if d[i]['m']>=40 and d[i]['m']!=None:
            t.append(d[i]['n'])
    return t
x=json.loads('[{"n":"Asha","m":91},{"n":"Ravi","m":35}]')
print(f(x))
print(f(x))
['Asha'] ['Asha', 'Asha']

Output की दूसरी line देखिए: दूसरी call पर list ["Asha", "Asha"] हो गई। यह मशहूर mutable default argument bug है – t=[] एक बार बनता है और हर call में साझा होता है। f, d, t, m, n जैसे नाम भी code का मतलब छिपाते हैं।

Python – after.py (clean)
"""Find students who passed an exam."""
import json

PASS_MARKS = 40


def passed_students(results: list[dict], pass_marks: int = PASS_MARKS) -> list[str]:
    """Return names of students whose marks are at least pass_marks."""
    return [r["name"] for r in results if r.get("marks") is not None and r["marks"] >= pass_marks]


def main() -> None:
    results = json.loads('[{"name": "Asha", "marks": 91}, {"name": "Ravi", "marks": 35}]')
    print(passed_students(results))
    print(passed_students(results))


if __name__ == "__main__":
    main()
['Asha'] ['Asha']
बदलावक्यों
अर्थपूर्ण नाम (passed_students, results)Code ख़ुद समझाता है
Constant PASS_MARKS“Magic numbers” नहीं; बदलने की एक जगह
Mutable default नहीं; नई list बनाएँछिपा bug ठीक
range(len()) की जगह comprehensionछोटा और साफ़
is not NoneNone से तुलना का सही तरीका
Type hints और docstringEditors और साथी जानते हैं क्या जाता और आता है
main() + if __name__ == "__main__"File import हो सके बिना चले

PEP 8 naming और layout

चीज़Styleउदाहरण
Variable, functionsnake_casetotal_fees, send_email()
ClassPascalCaseStudentReport
ConstantUPPER_SNAKEMAX_RETRIES = 3
Private helperशुरू में underscore_clean_name()
Indentation4 spaces, tabs कभी नहीं
Line length79–100 characters (team तय करे)
ImportsFile के ऊपर: standard library, third-party, आपके modules

Pythonic आदतें

Python – pythonic.py
students = ["Asha", "Ravi", "Neha"]
marks = [91, 58, 76]

# 1. enumerate instead of range(len())
for rank, name in enumerate(students, start=1):
    print(rank, name)

# 2. zip to walk two lists together
report = {name: m for name, m in zip(students, marks)}
print(report)

# 3. f-strings with formatting
fee = 12500.5
print(f"Fee: ₹{fee:,.2f} | Pass rate: {2/3:.0%}")

# 4. truthiness instead of len(x) == 0
pending = []
if not pending:
    print("No pending fees")

# 5. dict.get with a default
print(report.get("Kabir", "absent"))

# 6. unpacking
first, *others = students
print(first, others)
1 Asha 2 Ravi 3 Neha {'Asha': 91, 'Ravi': 58, 'Neha': 76} Fee: ₹12,500.50 | Pass rate: 67% No pending fees absent Asha ['Ravi', 'Neha']

Resources: हमेशा with इस्तेमाल करें

Python – with_files.py
# bad: file stays open if an error happens before close()
f = open("notes.txt", "w", encoding="utf-8")
f.write("Revise loops\n")
f.close()

# good: closed automatically, even on errors
with open("notes.txt", "a", encoding="utf-8") as f:
    f.write("Practise functions\n")

with open("notes.txt", encoding="utf-8") as f:
    print(f.read().strip())
Revise loops Practise functions

Errors को ख़ास तौर पर पकड़ें

Python – specific_errors.py
def read_age(text):
    try:
        age = int(text)
    except ValueError:                    # catch only what you expect
        return None
    if not 5 <= age <= 100:
        raise ValueError(f"age {age} out of range")
    return age

print(read_age("15"), read_age("fifteen"))
try:
    read_age("150")
except ValueError as e:
    print("Error:", e)
15 None Error: age 150 out of range
⚠️ खाली except कभी न लिखें

except: या except Exception: pass असली bugs छिपा देता है (typos और Ctrl+C भी)। सिर्फ़ वही exception पकड़ें जो संभाल सकते हैं, बाक़ी को log या re-raise करें।

एक काम वाले छोटे functions

  • Function एक काम करे और एक वाक्य में समझाया जा सके।
  • Function के अंदर print करने से बेहतर value लौटाना – लौटाई values test और दोबारा इस्तेमाल हो सकती हैं।
  • Global variables से बचें; data arguments से दें।
  • 4–5 से ज़्यादा parameters? उन्हें dataclass या dict में रखें।
  • साफ़ता के लिए keyword arguments: send(to="riya", retry=True)।
Python – dataclass.py
from dataclasses import dataclass

@dataclass
class Order:
    item: str
    price: float
    qty: int = 1

    @property
    def total(self) -> float:
        return self.price * self.qty

o = Order("Kaju Katli", 900, 2)
print(o)
print(o.total)
Order(item='Kaju Katli', price=900, qty=2) 1800

Tools से style जँचवाएँ

ToolकामCommand
ruffबहुत तेज़ linter: unused imports, bugs, style गड़बड़ीruff check .
black / ruff formatCode अपने-आप formatruff format .
mypyType hints जाँचता हैmypy app.py
pytestTests चलाता हैpytest

“before” program पर ruff चलाने से समस्याएँ अपने-आप मिलती हैं:

Python – before.py → ruff check --select E,F,B before.py
import json
def f(d,t=[]):
    for i in range(len(d)):
        if d[i]['m']>=40 and d[i]['m']!=None:
            t.append(d[i]['n'])
    return t
x=json.loads('[{"n":"Asha","m":91},{"n":"Ravi","m":35}]')
print(f(x))
print(f(x))
before.py:2:11: B006 Do not use mutable data structures for argument defaults before.py:4:41: E711 Comparison to `None` should be `cond is not None` Found 2 errors. 2 unsafe fixes available with `--fix --unsafe-fixes`.

Code review checklist

  1. नाम उद्देश्य बताएँ; छोटे loops के अलावा single letters नहीं।
  2. दोहराया code नहीं – दोहराया logic function में।
  3. Magic numbers नहीं – नाम वाले constants।
  4. Errors ख़ास तौर पर संभाले; खाली except नहीं।
  5. Files और connections with से खुले।
  6. Functions छोटे, values लौटाएँ, public के लिए docstrings।
  7. ज़रूरी नियमों के tests हों।
  8. ruff कोई warning न दिखाए; code formatted हो।

अभ्यास

  1. अपना कोई पुराना program लेकर हर variable को अर्थपूर्ण नाम दें।
  2. Items जमा करने वाले function में mutable default argument ढूँढकर ठीक करें।
  3. venv में ruff install करके project पर ruff check . चलाएँ और हर warning ठीक करें।
  4. Dictionary वाले record को computed property वाली dataclass में बदलें।

सारांश

  • PEP 8 नाम: snake_case, PascalCase, UPPER_SNAKE।
  • [] या {} जैसा mutable default argument कभी नहीं।
  • enumerate, zip, f-strings, with, comprehensions और specific exceptions।
  • छोटे functions, type hints, docstrings, main() guard।
  • Style ruff/black से और सही होना pytest से automate करें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या Python में type hints ज़रूरी हैं?
नहीं। Python runtime पर इन्हें नज़रअंदाज़ करता है। ये editors, linters, mypy और साथियों को code समझने में मदद करते हैं, इसलिए professional projects में आम हैं।
black इस्तेमाल करूँ या ruff format?
दोनों लगभग एक जैसा style देते हैं। ruff format बहुत तेज़ है और वही tool lint भी करता है, इसलिए कई नए projects दोनों काम ruff से करते हैं।
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
अगला topicPython Mini Projects आपकी प्रगति: 30 / 66 (45%) · Lesson 31 / 66 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें