सामग्री पर जाएँ

लेसन 147 · Practice and Review

Python चीट शीट

एक पेज की Python चीट शीट: सिंटैक्स, स्ट्रिंग, लिस्ट, डिक्शनरी, सेट, लूप, फ़ंक्शन, क्लास, एरर, फ़ाइलें, f-string फ़ॉर्मैट और सबसे ज़्यादा इस्तेमाल होने वाले बिल्ट-इन।

यह पेज पूरे कोर्स को एक जगह समेटता है: वह सिंटैक्स, डेटा टाइप और औज़ार जो आप रोज़ इस्तेमाल करेंगे, छोटे उदाहरणों में जिन्हें आप सेकंडों में स्कैन कर सकते हैं। कोड लिखने से पहले याददाश्त ताज़ा करने के लिए, अभ्यास प्रश्नों पर काम करते समय, या इंटरव्यू से ठीक पहले इसका इस्तेमाल कीजिए।

हर सेक्शन उस पाठ से जुड़ा है जो विषय को गहराई से समझाता है। लोगों को सबसे ज़्यादा उलझाने वाली कुछ बातों के लिए लाइव एडिटर हैं ताकि आप उन्हें काम करते देख सकें। यहाँ सब कुछ आधुनिक Python 3 है; जिन फ़ीचर को हाल के संस्करण चाहिए, उनके साथ यह लिखा है।

बुनियादी बातें

वेरिएबल, कमेंट और आउटपुट

Python
name = "Ada"                 # वेरिएबल को डिक्लेयर करने की ज़रूरत नहीं
age: int = 36                # वैकल्पिक टाइप हिंट
x, y = 3, 4                  # एक साथ कई असाइनमेंट
x, y = y, x                  # अदला-बदली
total = count = 0            # एक ही मान कई नामों को

print("Hi", name)            # Hi Ada
print("a", "b", sep="-")     # a-b
print("no newline", end="")
answer = input("Your name? ")  # हमेशा str लौटाता है

देखिए वेरिएबल, सिंटैक्स और इनपुट और आउटपुट।

मुख्य टाइप

टाइप उदाहरण बदला जा सकता है?
int 42, 1_000_000, 0xFF नहीं
float 3.14, 1e-3 नहीं
bool True, False नहीं
str "text", 'text', """multi-line""" नहीं
NoneType None नहीं
list [1, 2, 3] हाँ
tuple (1, 2), (1,) नहीं
dict {"a": 1} हाँ
set {1, 2}, खाली के लिए set() हाँ

int("7"), float("2.5"), str(10), list("abc"), bool(0) से बदलिए। type(x) से जाँचिए, या बेहतर, isinstance(x, int) से। देखिए डेटा टाइप और टाइप कन्वर्ज़न।

ऑपरेटर

Python
7 / 2      # 3.5   वास्तविक भाग
7 // 2     # 3     फ़्लोर डिवीज़न
7 % 2      # 1     शेषफल
2 ** 10    # 1024  घात
-7 // 2    # -4    ऋणात्मक अनंत की ओर फ़्लोर होता है

x += 1                     # इनके अलावा -=, *=, /=, //=, %=, **= भी
0 < x < 10                 # जंजीर वाली तुलना
a == b, a is b             # बराबर मान बनाम वही ऑब्जेक्ट
x in items, x not in items
not a, a and b, a or b     # ऑपरेंड में से एक लौटाते हैं
name or "guest"            # खाली मानों के लिए विकल्प
if (n := len(items)) > 3:  # वॉलरस: एक्सप्रेशन के भीतर असाइन करें
    print(n)

देखिए अंकगणितीय ऑपरेटर, तुलना और लॉजिकल ऑपरेटर और सदस्यता और पहचान।

स्ट्रिंग

Python
s = "Hello, World"
s[0], s[-1], s[7:12]       # 'H', 'd', 'World'
len(s)                     # 12
s.lower(), s.upper(), s.title()
s.strip(), s.lstrip("x"), s.rstrip()
s.split(", ")              # ['Hello', 'World']
"-".join(["a", "b"])       # 'a-b'
s.replace("World", "you")
s.startswith("He"), s.endswith("!")
s.find("o"), s.count("l")  # 4, 3   (find गायब होने पर -1 लौटाता है)
"42".isdigit(), "abc".isalpha()
"ab" * 3                   # 'ababab'
r"C:\new\folder"           # रॉ स्ट्रिंग: बैकस्लैश जस के तस रहते हैं

स्ट्रिंग अपरिवर्तनीय (immutable) हैं: हर मेथड नई स्ट्रिंग लौटाती है। देखिए स्ट्रिंग और स्ट्रिंग मेथड।

f-string और फ़ॉर्मैट स्पेक

स्पेक उदाहरण नतीजा
दशमलव f"{3.14159:.2f}" 3.14
हज़ार विभाजक f"{1234567:,}" 1,234,567
प्रतिशत f"{0.256:.1%}" 25.6%
चौड़ाई, अलाइनमेंट f"[{'ab':>5}]", f"[{'ab':<5}]", f"[{'ab':^6}]" [ ab], [ab ], [ ab ]
शून्य से भरना f"{7:03}" 007
चिह्न f"{5:+}" +5
डीबग f"{x=}" x=10
तारीखें f"{d:%Y-%m-%d}" 2026-10-14
Python फ़ॉर्मैट स्पेक अमल में

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

देखिए स्ट्रिंग फ़ॉर्मैटिंग।

लिस्ट, ट्यूपल और स्लाइसिंग

Python
nums = [3, 1, 4]
nums.append(1)          # [3, 1, 4, 1]
nums.extend([5, 9])     # कई जोड़ें
nums.insert(0, 2)       # इंडेक्स 0 पर
nums.remove(1)          # पहला मेल खाता मान
nums.pop()              # हटाओ + आख़िरी लौटाओ (इंडेक्स i के लिए pop(i))
nums.index(4), nums.count(1)
nums.sort()             # उसी जगह, None लौटाता है
sorted(nums, reverse=True)       # नई लिस्ट
sorted(words, key=len)           # किसी कुंजी से सॉर्ट
nums.reverse(); nums[::-1]       # उसी जगह बनाम उलटी कॉपी
first, *rest = nums              # तारे के साथ अनपैकिंग
point = (3, 4); x, y = point     # ट्यूपल: तय, अपरिवर्तनीय

स्लाइस seq[start:stop:step] हैं; stop शामिल नहीं होता और कोई भी हिस्सा छोड़ा जा सकता है।

स्लाइस मतलब
a[2:5] आइटम 2, 3, 4
a[:3] / a[-3:] पहले तीन / आख़िरी तीन
a[::2] हर दूसरा आइटम
a[::-1] उलटी कॉपी
a[:] उथली कॉपी (shallow copy)

देखिए लिस्ट, लिस्ट मेथड, ट्यूपल, स्लाइसिंग और अनपैकिंग।

डिक्शनरी और सेट

Python
user = {"name": "Ana", "age": 30}
user["email"] = "[email protected]"   # जोड़ें / अपडेट करें
user.get("phone", "n/a")            # KeyError की जगह डिफ़ॉल्ट
user.setdefault("tags", []).append("admin")
user.pop("age")                     # हटाओ + लौटाओ
"name" in user                      # कुंजियाँ जाँचता है
for key, value in user.items(): ...
user.keys(), user.values()
merged = defaults | user            # 3.9+: दायाँ पक्ष जीतता है
user |= {"active": True}            # उसी जगह अपडेट

a, b = {1, 2, 3}, {3, 4}
a | b, a & b, a - b, a ^ b          # यूनियन, इंटरसेक्शन, अंतर, सिमेट्रिक
a.add(9); a.discard(7)              # discard कभी एरर नहीं उठाता

देखिए डिक्शनरी, डिक्शनरी मेथड और सेट। गिनती और ग्रुपिंग के लिए collections के Counter और defaultdict इस्तेमाल कीजिए।

कॉम्प्रिहेंशन

Python
squares = [n * n for n in range(10)]
evens = [n for n in nums if n % 2 == 0]
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
pairs = [(r, c) for r in range(3) for c in range(3)]
lengths = {word: len(word) for word in words}     # dict
initials = {name[0] for name in names}            # set
total = sum(n * n for n in nums)                  # जनरेटर, कोई लिस्ट नहीं बनी

देखिए लिस्ट कॉम्प्रिहेंशन और कॉम्प्रिहेंशन।

कंट्रोल फ़्लो

Python
if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
else:
    grade = "C"
status = "adult" if age >= 18 else "minor"

for i, item in enumerate(items, start=1): ...
for a, b in zip(names, scores): ...
for n in range(10, 0, -2): ...     # 10 8 6 4 2
while attempts < 3: ...
break, continue                    # लूप छोड़ें / अगले चक्र पर जाएँ
for ... else:                      # लूप break न हुआ हो तो else चलता है

match command.split():
    case ["go", direction]:
        move(direction)
    case ["quit" | "exit"]:
        stop()
    case _:
        print("Unknown")

देखिए if स्टेटमेंट, for लूप, while लूप, break, continue और else और match।

फ़ंक्शन

Python
def greet(name: str, greeting: str = "Hello") -> str:
    """Return a greeting."""
    return f"{greeting}, {name}!"

greet("Ada"); greet("Ada", greeting="Hi")

def report(*args, **kwargs): ...      # अतिरिक्त पोज़ीशनल / कीवर्ड आर्ग्युमेंट
def move(x, y, /, *, speed=1): ...    # केवल-पोज़ीशनल / केवल-कीवर्ड
report(*values, **options)            # कॉल करते समय अनपैक करें

square = lambda n: n * n
sorted(people, key=lambda p: p["age"])

म्यूटेबल डिफ़ॉल्ट आर्ग्युमेंट एक बार बनते हैं, जब फ़ंक्शन परिभाषित होता है, और हर कॉल उन्हें साझा करता है। डिफ़ॉल्ट के रूप में None इस्तेमाल कीजिए और लिस्ट भीतर बनाइए।

Python म्यूटेबल डिफ़ॉल्ट का जाल

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

स्कोप LEGB का पालन करता है: Local, Enclosing, Global, Built-in। किसी नाम को असाइन करने पर वह लोकल बन जाता है, जब तक आप global या nonlocal घोषित न करें। देखिए फ़ंक्शन, आर्ग्युमेंट, स्कोप और लैम्ब्डा।

डेकोरेटर, जनरेटर और इटरेशन के औज़ार

Python
from functools import wraps, cache

def logged(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print("calling", func.__name__)
        return func(*args, **kwargs)
    return wrapper

@cache                                 # नतीजे याद रखें
def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)

def countdown(n):
    while n > 0:
        yield n                        # यहाँ रुकता है, next() पर आगे बढ़ता है
        n -= 1

any(x > 3 for x in nums), all(nums), min(nums, key=abs)
map(str, nums), filter(None, values)   # आलसी इटरेटर

देखिए डेकोरेटर, जनरेटर, इटरेटर और itertools और functools।

क्लास

Python
from dataclasses import dataclass

class Account:
    bank = "PyBank"                         # क्लास एट्रिब्यूट

    def __init__(self, owner: str, balance: float = 0) -> None:
        self.owner = owner                  # इंस्टेंस एट्रिब्यूट
        self._balance = balance             # "_" = परंपरा से आंतरिक

    def deposit(self, amount: float) -> None:
        self._balance += amount

    @property
    def balance(self) -> float:             # एट्रिब्यूट की तरह पढ़ें
        return self._balance

    @classmethod
    def empty(cls, owner): return cls(owner)

    @staticmethod
    def is_valid(amount): return amount > 0

    def __repr__(self) -> str:
        return f"Account({self.owner!r}, {self._balance})"

class Savings(Account):                     # इनहेरिटेंस
    def __init__(self, owner, balance=0, rate=0.02):
        super().__init__(owner, balance)
        self.rate = rate

@dataclass(order=True, frozen=True)         # __init__, __repr__, __eq__ मुफ़्त में
class Point:
    x: float
    y: float = 0.0

देखिए क्लास, मेथड, इनहेरिटेंस, स्पेशल मेथड, प्रॉपर्टी, डेटा क्लास और Enum।

एरर और एक्सेप्शन

Python
try:
    value = int(text)
except ValueError as error:
    print("Not a number:", error)
except (TypeError, KeyError):
    ...
else:
    print("runs only if no exception")
finally:
    print("always runs")

raise ValueError("age must be positive")
raise RuntimeError("save failed") from error   # कारण बनाए रखें

class InsufficientFunds(Exception):
    pass

आम बिल्ट-इन एक्सेप्शन: ValueError, TypeError, KeyError, IndexError, AttributeError, ZeroDivisionError, FileNotFoundError, StopIteration। देखिए एक्सेप्शन, एक्सेप्शन उठाना और कस्टम एक्सेप्शन।

फ़ाइलें और डेटा

Python
from pathlib import Path
import csv, json

with open("notes.txt", "w", encoding="utf-8") as f:   # "w" "a" "r" "x"
    f.write("line 1\n")
with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip())

path = Path("data") / "report.txt"
path.parent.mkdir(exist_ok=True)
path.write_text("hi", encoding="utf-8"); path.read_text(encoding="utf-8")
list(Path(".").glob("*.py"))

data = json.loads('{"a": 1}'); text = json.dumps(data, indent=2)
with open("rows.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"])

देखिए फ़ाइलें, pathlib, CSV, JSON और कॉन्टेक्स्ट मैनेजर।

सबसे ज़्यादा इस्तेमाल होने वाले बिल्ट-इन

फ़ंक्शन क्या करता है
len(x) आइटम की संख्या
range(start, stop, step) पूर्णांकों का क्रम (stop शामिल नहीं)
enumerate(it, start=0) (index, item) जोड़े
zip(a, b, strict=False) कई इटरेबल के आइटम जोड़ी में मिलाता है
sorted(it, key=, reverse=) नई सॉर्ट की हुई लिस्ट
reversed(seq) उलटा इटरेटर
sum, min, max कुल और चरम मान (min/max में key= चलता है)
any, all क्या कम से कम एक / हर आइटम ट्रूदी (truthy) है?
map(f, it), filter(f, it) आलसी रूपांतरण / चयन
abs, round(x, n), divmod(a, b), pow(a, b, mod) संख्या के सहायक
isinstance(obj, cls) टाइप जाँच जो इनहेरिटेंस का सम्मान करती है
getattr, setattr, hasattr डायनेमिक एट्रिब्यूट एक्सेस
open(path, mode, encoding=) फ़ाइल खोलना
input(prompt), print(*items) कंसोल I/O
id(x), type(x), dir(x), help(x) निरीक्षण

काम के स्टैंडर्ड लाइब्रेरी मॉड्यूल

मॉड्यूल किसके लिए इस्तेमाल करें
math, random, statistics गणित फ़ंक्शन, रैंडम चुनाव, माध्य/माध्यिका
datetime, zoneinfo तारीखें, समय, टाइम ज़ोन
collections Counter, defaultdict, deque, namedtuple
itertools, functools chain, groupby, pairwise; cache, partial, reduce
re रेगुलर एक्सप्रेशन
pathlib, os, shutil पाथ, फ़ोल्डर, फ़ाइलें कॉपी करना
json, csv, sqlite3 डेटा फ़ॉर्मैट और बिल्ट-इन डेटाबेस
asyncio async/await से कन्करेंट I/O
logging, unittest, argparse लॉग, टेस्ट, कमांड-लाइन विकल्प

देखिए मॉड्यूल, पैकेज और pip और वर्चुअल एनवायरनमेंट।

याद रखने लायक जाल

दो और क्लासिक: लिस्ट की लिस्ट कॉपी करना, और फ़्लोट की तुलना।

Python उथली कॉपी और फ़्लोट की तुलना

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • is पहचान (identity) जाँचता है: इसे केवल None के साथ इस्तेमाल कीजिए (if x is None)। मानों की तुलना == से कीजिए।
  • खाली कंटेनर, 0, "" और None फ़ॉल्सी (falsy) हैं: if items: का मतलब है "अगर लिस्ट खाली नहीं है"।
  • list.sort() None लौटाती है; sorted() नई लिस्ट लौटाती है।
  • लिस्ट पर लूप चलाते हुए उसे बदलने से आइटम छूट जाते हैं। कॉपी पर लूप चलाइए या नई लिस्ट बनाइए।
  • लूप में क्लोज़र वेरिएबल का अंतिम मान देखते हैं; ज़रूरत हो तो उसे डिफ़ॉल्ट आर्ग्युमेंट (lambda i=i: i) से बाँधिए।

अपनी समझ जाँचें

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. f"{0.075:.1%}" क्या नतीजा देता है?

    % स्पेक 100 से गुणा करता है और दिए गए दशमलव स्थान दिखाता है।
  2. 2. def add(item, items=[]) से आपको क्यों बचना चाहिए?

    डिफ़ॉल्ट का मूल्यांकन फ़ंक्शन परिभाषित होते समय एक बार होता है। None इस्तेमाल कीजिए और लिस्ट फ़ंक्शन के भीतर बनाइए।
  3. 3. [1, 2, 3, 4, 5][::-2] क्या है?

    -2 का स्टेप अंत से शुरू होता है और हर दूसरा आइटम लेता है।
  4. 4. कौन-सी लाइन डिक्शनरी की उस कुंजी को सुरक्षित रूप से पढ़ती है जो गायब हो सकती है?

    get() KeyError उठाने की जगह डिफ़ॉल्ट लौटाता है। [] से इंडेक्सिंग or के मूल्यांकन से पहले ही एरर उठा देती है।

सारांश

  • कोड लिखते समय इस पेज को खुला रखिए: यह सिंटैक्स, मुख्य टाइप, स्ट्रिंग, संग्रह, कंट्रोल फ़्लो, फ़ंक्शन, क्लास, एरर और फ़ाइलों को कवर करता है।
  • सबसे पेचीदा बातें फ़ॉर्मैट स्पेक, म्यूटेबल डिफ़ॉल्ट आर्ग्युमेंट, उथली कॉपी और फ़्लोट तुलना हैं; ऊपर के लाइव एडिटर हर एक को दिखाते हैं।
  • जब आपको ब्योरे चाहिए, हर सेक्शन पूरे पाठ से जुड़ा है।

अगला: Python अभ्यास प्रश्न, जहाँ आप इस चीट शीट को ग्रेड किए गए सवालों पर काम में लगाएँगे।

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।