← Back

Home › Hindi › Python Cheat Sheet Hindi में

Python Cheat Sheet — एक page में सारा ज़रूरी reference

🌐 यह page Hindi में है · Read this in English →

Data typesसारे methodsLoops + functionsErrors और fix

Data types और basics

# बदलने योग्य (mutable) बनाम न बदलने योग्य (immutable)
x = 5                 # int       immutable
y = 3.14              # float     immutable
s = "Asha"            # str       immutable
t = (1, 2)            # tuple     immutable
lst = [1, 2]          # list      mutable
d = {"a": 1}          # dict      mutable
st = {1, 2}           # set       mutable
flag = True           # bool      immutable
nothing = None        # NoneType  immutable

print(type(x), type(lst))       #  

# conversion
int("42"), float("3.5"), str(42)
int(3.9)                # 3   — truncate होता है, round नहीं
round(3.9)              # 4
str(42) + "items"       # '42items'

# f-string — formatting का standard तरीका
name, score = "Asha", 91.456
f"{name} scored {score:.1f}"     # 'Asha scored 91.5'
f"{score:>8.2f}"                 # right-align, 2 decimals

List — सारे काम के methods

a = [3, 1, 2]

a.append(4)             # अंत में एक item       -> [3,1,2,4]
a.extend([5, 6])        # कई items जोड़ो        -> [3,1,2,4,5,6]
a.insert(0, 0)          # position पर डालो       -> [0,3,1,2,4,5,6]
a.remove(3)             # पहला 3 हटाओ            -> [0,1,2,4,5,6]
a.pop()                 # आखिरी निकालो + return -> 6
a.pop(0)                # index से निकालो       -> 0
a.sort()                # in-place, None देता है
a.reverse()             # in-place, None देता है
a.clear()               # सब खाली

b = [3, 1, 2]
sorted(b)               # नई list return करता है  -> [1,2,3]
sorted(b, reverse=True) # घटते क्रम में
len(b), max(b), min(b), sum(b)

# slicing — stop हमेशा exclusive
b[0], b[-1], b[1:3], b[:2], b[2:], b[::2], b[::-1]

# comprehension
[x * 2 for x in b if x > 1]

सबसे बड़ा जाल: sort(), append(), reverse() सब None return करते हैं। a = a.sort() लिखोगे तो a None हो जाएगा।

String, dict और set

s = "  Python is Fun  "

s.strip(), s.lstrip(), s.rstrip()      # whitespace हटाओ
s.lower(), s.upper(), s.title()
s.replace("Fun", "Easy")
s.split(), "-".join(["a", "b"])        # 'a-b'
s.startswith("Py"), s.endswith("un")
s.find("is"), s.count("n"), s.isdigit()
len(s), s[0], s[-1], s[::-1]           # उल्टा

d = {"name": "Asha", "marks": 91}
d["name"]                              # KeyError अगर key न हो
d.get("age", 0)                        # सुरक्षित — default देता है
"name" in d                            # membership
d.keys(), d.values(), d.items()
d["city"] = "Delhi"                    # नई key
d.update({"age": 20})
d.pop("age", None)                     # default के साथ सुरक्षित
for k, v in d.items(): print(k, v)

st = {1, 2, 3}
st.add(4), st.discard(9)               # discard KeyError नहीं देता
st | {5, 6}        # union
st & {2, 3}        # intersection
st - {2}           # difference
set([1, 1, 2])     # duplicate हटाने का सबसे तेज़ तरीका

Loops और conditions

for i in range(5):        # 0,1,2,3,4  — stop exclusive
for i in range(2, 8):     # 2..7
for i in range(10, 0, -2) # 10,8,6,4,2 — उल्टा, step ज़रूरी
for i, x in enumerate(items):          # index + item
for i, x in enumerate(items, 1):       # गिनती 1 से
for a, b in zip(list1, list2):         # दो lists साथ

while count < 10:
    count += 1                         # update भूल गए = infinite loop

break        # पूरा loop बंद
continue     # सिर्फ यह बार छोड़ो
else:        # loop बिना break खत्म हुआ तो

# conditions
x == y   x != y   x > y   x >= y
a and b, a or b, not a
value in items, value not in items
result = a if condition else b         # ternary

# truthy/falsy: 0, "", [], {}, set(), None  -> False

Functions

def area(width, height=10):        # default argument
    '''Rectangle का area।'''       # docstring
    return width * height          # return भूले तो None मिलेगा

area(5)                            # positional
area(width=5, height=3)            # keyword
area(5, *more)                     # *args -> tuple
area(**options)                    # **kwargs -> dict

lam = lambda n: n * 2              # एक-expression function
sorted(rows, key=lambda r: r["marks"])

def outer():                       # closure
    total = 0
    def bump():
        nonlocal total             # global नहीं, nonlocal
        total += 1
    return bump

yield                              # generator — एक-एक item देता है

Default argument में कभी mutable मत रखो — def f(x, box=[]) सब calls एक ही list share करती हैं। box=None रखो और अंदर बनाओ।

Errors — message और एक-line fix

# error संभालने का standard ढाँचा
try:
    value = int(raw)
except ValueError as e:
    print(f"number नहीं है: {e}")
else:
    print("सही चला")           # सिर्फ जब exception न आए
finally:
    cleanup()                   # हर हाल में चलेगा

raise ValueError("साफ़ message")   # खुद error फेंकना

Traceback हमेशा नीचे से ऊपर पढ़ो: आखिरी line error बताती है, उसके ऊपर वाली lines बताती हैं कि वहाँ तक कैसे पहुँचे।

🛠️ Practice करो (free, browser में)

पढ़ना काफी नहीं — यही bug खुद fix करके देखो। नीचे के problems browser में ही चलते हैं, कोई install नहीं, कोई login नहीं।

सारे free problems देखो →

अक्सर पूछे जाने वाले सवाल

Cheat sheet से Python सीख सकते हैं?

सीखने के लिए नहीं, याद रखने के लिए हाँ। Cheat sheet तब काम आता है जब concept पहले समझ आ चुका हो और सिर्फ syntax या method का नाम याद न आ रहा हो। नए topic के लिए guide पढ़ो, फिर यहाँ revision करो।

सबसे ज़्यादा भूल जाने वाली चीज़ें कौन-सी हैं?

चार चीज़ें बार-बार भूलती हैं: sort() और append() None return करते हैं; slice में stop exclusive है; input() हमेशा string देता है; और range(1, 10) में 10 शामिल नहीं है। ये चार याद रख लो तो आधी गलतियाँ खत्म।

Mutable और immutable क्यों मायने रखता है?

क्योंकि इसी से तय होता है कि क्या dict की key बन सकता है, क्या set में जा सकता है, और क्या function के अंदर बदलने पर caller पर असर पड़ेगा। List, dict और set mutable हैं; number, string, tuple और None immutable।

Interview से पहले क्या revise करें?

Data types और mutability, list/tuple/dict/set के methods, loops में break-continue, functions में scope और default arguments, और error messages के fix। उसके ऊपर रोज़ output prediction की practice — यही असली interview format है।

आगे पढ़ो