चीट शीट

Python cheat sheet: syntax, commands और built-in functions तालिकाओं में

अपडेट किया गया: · Skillaria.Top

Python का syntax indentation पर चलता है, न कि curly braces पर: colon के बाद का block 4 spaces से आगे बढ़ता है। मूल बातें हैं बिना type घोषित किए variables, if/elif/else की शर्तें, for और while loops, def से functions, और built-in functions जैसे print, len, range, input, type, साथ में strings, lists और dictionaries के methods।

यह Python cheat sheet पहले कुछ महीनों के लिए ज़रूरी सब कुछ एक पन्ने पर रखती है: Python syntax, loops, built-in functions, string, list और dictionary के methods, और terminal commands। हर तालिका एक छोटा संदर्भ है, जिसके उदाहरण सीधे REPL में डाले जा सकते हैं।

Python syntax की मूल बातें

भाषा की मुख्य विशेषता: blocks braces से नहीं, indentation से बनते हैं। Colon वाली line के बाद (if, for, def, class) की lines 4 spaces से आगे बढ़ती हैं। Tabs और spaces को मिलाना मना है — IndentationError आएगा।

Constructionउदाहरणस्पष्टीकरण
Comment# text# से लेकर line के अंत तक सब कुछ अनदेखा
Variableage = 25type घोषित नहीं होता, value से तय होता है
एक साथ assignmenta, b = 1, 2unpacking; values की अदला-बदली: a, b = b, a
Outputprint("नमस्ते", name)arguments के बीच एक space
Inputs = input("नाम: ")हमेशा string लौटाता है
f-stringf"{name}: {price:.2f}"expressions का भीतर लगाना और format
Type annotationcount: int = 0IDE और checkers के लिए संकेत, run के समय जाँच नहीं होती
खाली blockpassplaceholder, जहाँ syntax को body चाहिए
Importfrom math import sqrtmodule या उसके किसी नाम को जोड़ना

डेटा types

TypeLiteralबदला जा सकता है
int42, 1_000_000नहीं
float3.14, 1e-3नहीं
boolTrue, Falseनहीं
str"पाठ", 'पाठ', """कई पंक्तियाँ"""नहीं
list[1, 2, 3]हाँ
tuple(1, 2), (1,)नहीं
dict{"a": 1}हाँ
set{1, 2}, खाली — set()हाँ
NoneTypeNone—

Operators

समूहOperatorsउदाहरण → नतीजा
गणित+ - * / // % **7 // 2 → 3, 7 % 2 → 1, 2 ** 10 → 1024
तुलना== != < > <= >=1 < x < 10 — तुलना की चेन
तर्कand or notx or "डिफ़ॉल्ट"
सदस्यताin, not in"a" in "abc" → True
पहचानis, is notx is None
असाइनमेंट+= -= *= /=, :=if (n := len(s)) > 10: ...

शर्तें और pattern matching

if score >= 90:
    grade = "A"
elif score >= 70:
    grade = "B"
else:
    grade = "C"

status = "वयस्क" if age >= 18 else "बच्चा"   # ternary operator

match command:
    case "start":
        print("शुरू")
    case "stop" | "exit":
        print("रुका")
    case _:
        print("अज्ञात कमांड")

ये values झूठी मानी जाती हैं: False, None, 0, खाली string और खाली collections। इसलिए if len(items) > 0 की जगह बस if items लिखा जाता है।

Python loops: for और while का syntax

for loop

Python के for loop का syntax: for variable in sequence: और 4 spaces वाला body। Loop कोई भी iterable घुमा सकता है — string, list, dictionary, file, range।

for i in range(5):              # 0 1 2 3 4
    print(i)

for i in range(10, 0, -2):      # 10 8 6 4 2
    print(i)

for i, fruit in enumerate(["सेब", "नाशपाती"], start=1):
    print(i, fruit)

for name, score in zip(names, scores):
    print(name, score)

for key, value in prices.items():
    print(key, value)

while loop

attempts = 3
while attempts > 0:
    password = input("पासवर्ड: ")
    if password == "secret":
        print("लॉग इन हो गया")
        break
    attempts -= 1
else:
    print("प्रयास ख़त्म हो गए")   # चलता है, अगर break नहीं हुआ
Commandक्या करता है
breakloop से समय से पहले बाहर निकलता है
continueअगले iteration पर जाता है
loop का elseतब चलता है, जब loop बिना break के पूरा हो
range(stop), range(start, stop, step)संख्याओं का क्रम, stop शामिल नहीं

List comprehensions

squares = [x ** 2 for x in range(10)]
evens = [x for x in numbers if x % 2 == 0]
lengths = {word: len(word) for word in words}
unique = {c.lower() for c in text}
total = sum(x * x for x in range(100))   # generator expression

Functions

def greet(name: str, greeting: str = "नमस्ते") -> str:
    """स्वागत का संदेश लौटाता है।"""
    return f"{greeting}, {name}!"

def total(*args, **kwargs):
    return sum(args), kwargs

square = lambda x: x * x
print(greet("प्रिया"))                 # नमस्ते, प्रिया!
print(greet("प्रिया", greeting="हैलो"))  # हैलो, प्रिया!
तत्वअर्थ
def f(a, b=1)डिफ़ॉल्ट मान वाला parameter
*argsकितने भी positional arguments (tuple)
**kwargsकितने भी named arguments (dictionary)
returnमान लौटाना; उसके बिना function None लौटाएगा
lambda x: ...एक expression वाला छोटा अनाम function
global, nonlocalबाहरी scope के variable को बदलना

डिफ़ॉल्ट के रूप में बदले जा सकने वाला मान न लें, जैसे def f(items=[]): list एक बार बनती है और calls के बीच जमा होती रहती है। सही तरीका है items=None और भीतर if items is None: items = []।

Built-in functions

Python के built-in functions बिना import के उपलब्ध हैं। ये मुख्य functions हैं जो लगभग हर script में दिखते हैं।

Functionक्या करता हैउदाहरण → नतीजा
print()values दिखाता हैprint(1, 2, sep="-") → 1-2
input()keyboard से string पढ़ता हैint(input())
len()collection या string की लंबाईlen("abc") → 3
type()object का typetype(3.0) → <class 'float'>
isinstance()type की जाँचisinstance(5, int) → True
int() float() str() bool()types बदलनाint("42") → 42
list() tuple() set() dict()collections बनानाlist("ab") → ['a', 'b']
range()संख्याओं का क्रमlist(range(3)) → [0, 1, 2]
enumerate()(index, element) की जोड़ियाँlist(enumerate("ab")) → [(0, 'a'), (1, 'b')]
zip()sequences को जोड़ी-दर-जोड़ी मिलानाlist(zip([1, 2], "ab")) → [(1, 'a'), (2, 'b')]
sum() min() max()योग, न्यूनतम, अधिकतमmax([3, 7, 1]) → 7
abs() round()निरपेक्ष मान और गोलीकरणround(3.14159, 2) → 3.14
sorted()नई क्रमबद्ध listsorted(words, key=len, reverse=True)
reversed()उल्टे क्रम का iteratorlist(reversed([1, 2])) → [2, 1]
map() filter()function लगाना / छाननाlist(map(str, [1, 2])) → ['1', '2']
any() all()कम से कम एक / सभी सचall(x > 0 for x in nums)
open()file खोलनाopen("a.txt", encoding="utf-8")
help() dir()सहायता और attributes की सूचीhelp(str.split), dir(list)
id() hash()object की पहचान और hashhash("a")

सबसे सुविधाजनक Python reference हमेशा साथ रहता है — REPL में help() function: help(dict) dictionary के सभी methods विवरण के साथ दिखाएगा, और dir(obj) उपलब्ध नामों की सूची।

String methods

Python strings: string बदली नहीं जा सकती, हर method नई string लौटाता है। Slices list की तरह काम करते हैं: s[1:4], और s[::-1] — उल्टा।

Methodउदाहरण → नतीजा
upper() lower()"Py".upper() → 'PY'
capitalize() title()"hello world".title() → 'Hello World'
strip() lstrip() rstrip()" hi \n".strip() → 'hi'
split(sep)"a,b,c".split(",") → ['a', 'b', 'c']
join(iterable)"-".join(["a", "b"]) → 'a-b'
replace(old, new)"cat".replace("c", "b") → 'bat'
find() index()"hello".find("l") → 2; न मिले तो -1 (index में — त्रुटि)
count()"banana".count("a") → 3
startswith() endswith()"file.py".endswith(".py") → True
isdigit() isalpha() isspace()"123".isdigit() → True
removeprefix() removesuffix()"test_a".removeprefix("test_") → 'a'
zfill() center() ljust()"7".zfill(3) → '007'
format()"{} + {}".format(1, 2) → '1 + 2'

List commands

List एक बदली जा सकने वाली क्रमबद्ध collection है। ज़्यादातर methods list को उसी जगह बदलते हैं और None लौटाते हैं, इसलिए a = a.sort() आम गलती है।

संक्रियाक्या करता हैउदाहरण
append(x)अंत में जोड़ता हैa.append(4)
extend(iter)सभी elements जोड़ता हैa.extend([5, 6])
insert(i, x)index पर डालता हैa.insert(0, "first")
remove(x)मान की पहली मौजूदगी हटाता हैa.remove(3)
pop(i)element हटाकर लौटाता है (डिफ़ॉल्ट — आख़िरी)last = a.pop()
clear()list खाली करता हैa.clear()
index(x)पहली मौजूदगी का indexa.index("b")
count(x)कितनी बार आयाa.count(1)
sort()उसी जगह क्रमबद्ध करता हैa.sort(key=str.lower)
reverse()उसी जगह उल्टा करता हैa.reverse()
copy()उथली प्रति (shallow copy)b = a.copy()
del a[i]index या slice से हटानाdel a[1:3]
Slicesa[start:stop:step]a[-1] — आख़िरी, a[:3] — पहले तीन

Dictionary commands

संक्रियाक्या करता हैउदाहरण
d[key]key का मान; key न हो तो KeyErrord["name"]
get(key, default)मान या विकल्पd.get("age", 0)
d[key] = valueजोड़ना या बदलनाd["city"] = "जयपुर"
keys() values() items()keys, values, जोड़ियाँfor k, v in d.items():
update()दूसरे dictionary से मिलानाd.update({"a": 1})
d1 | d2नया जुड़ा हुआ dictionarymerged = defaults | user
pop(key, default)हटाकर मान लौटानाd.pop("tmp", None)
popitem()आख़िरी जोड़ी हटानाd.popitem()
setdefault(key, value)मान लौटाना, और key न हो तो बनानाd.setdefault("tags", []).append("py")
key in dkey मौजूद है या नहींif "name" in d:
dict.fromkeys()एक मान वाले keys से dictionarydict.fromkeys("abc", 0)
len(d), del d[key]आकार और हटानाdel d["old"]

Tuples और sets

संक्रियाउदाहरण → नतीजा
Tuple unpackingx, y = (3, 4)
Set में जोड़नाs.add(5), हटाना — s.discard(5)
Union / intersection{1, 2} | {2, 3} → {1, 2, 3}; {1, 2} & {2, 3} → {2}
Difference{1, 2} - {2} → {1}
List से दोहराव हटानाlist(dict.fromkeys(items)) — क्रम बनाए रखते हुए

Exceptions और files

try:
    number = int(input("संख्या: "))
except ValueError as err:
    print("यह संख्या नहीं है:", err)
else:
    print("सफल")
finally:
    print("हमेशा चलता है")

with open("data.txt", "w", encoding="utf-8") as f:
    f.write("पंक्ति\n")

with open("data.txt", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip())
Exceptionकब आता है
SyntaxError, IndentationErrorsyntax या indentation में गलती
NameErrorनाम परिभाषित नहीं (typo)
TypeErrorगलत type पर operation: "1" + 1
ValueErrorसही type, पर गलत मान: int("abc")
IndexError, KeyErrorऐसा index या key नहीं है
FileNotFoundErrorfile नहीं मिली
ZeroDivisionErrorशून्य से भाग

Classes

from dataclasses import dataclass

class Dog:
    def __init__(self, name: str):
        self.name = name

    def bark(self) -> str:
        return f"{self.name}: भौं-भौं!"

@dataclass
class Point:
    x: float
    y: float

print(Dog("टॉमी").bark())   # टॉमी: भौं-भौं!
print(Point(1, 2))          # Point(x=1, y=2)

Built-in modules

Standard library interpreter के साथ आती है — बस import करना काफ़ी है।

Moduleकिसके लिएउदाहरण
mathगणितmath.sqrt(16) → 4.0
randomयादृच्छिक संख्याएँrandom.randint(1, 6), random.choice(items)
datetimeतारीख और समयdatetime.date.today()
pathlibpaths और filesPath("data").glob("*.csv")
os, syssystem, environment variables, argumentsos.environ.get("HOME"), sys.argv
jsonJSON पढ़ना और लिखनाjson.loads(text), json.dumps(obj, ensure_ascii=False)
csvCSV tablescsv.DictReader(f)
collectionsCounter, defaultdict, dequeCounter("banana").most_common(1) → [('a', 3)]
itertoolsiterators के combinations और chainsitertools.chain(a, b)
reregular expressionsre.findall(r"\d+", s)
timeरुकना और समय मापनाtime.sleep(1), time.perf_counter()
asyncioasynchronous codeasyncio.run(main())

Python 3.15 में lazy import आया (PEP 810): lazy import pandas as pd module को उसके पहले इस्तेमाल तक लोड होने से रोकता है, और भारी dependencies वाला script काफ़ी तेज़ शुरू होता है।

Python commands terminal में

“Python commands” वाली खोज का अलग हिस्सा वे commands हैं जो interpreter चलाती हैं और libraries install करती हैं। Windows पर python3 की जगह आम तौर पर python या py लिखा जाता है।

Commandक्या करता है
python3 --versionversion दिखाता है
python3interactive console REPL खोलता है (बाहर — exit())
python3 script.pyfile चलाता है
python3 -c "print(2 + 2)"एक line चलाता है
python3 -m venv .venvvirtual environment बनाता है
source .venv/bin/activate / .venv\Scripts\activateenvironment चालू करता है (Linux, macOS / Windows)
python3 -m pip install requestspackage install करता है
pip list, pip freeze > requirements.txtpackages की सूची और उसे सहेजना
pip install -r requirements.txtfile से dependencies install करता है
python3 -m http.server 8000मौजूदा folder में सरल web server
uv init, uv add requests, uv run main.pyuv tool से project, dependency और run

नए लोगों की आम गलतियाँ

  • शर्त में = से तुलना — शर्त में == चाहिए; एक = असाइनमेंट है।
  • colon भूल जाना if, for, def के बाद — SyntaxError।
  • string और number जोड़ना: "उम्र: " + 25 गलत है, लिखें f"उम्र: {25}"।
  • loop के दौरान list बदलना — copy पर चलाएँ for x in a[:] या नई list बनाएँ।
  • input() string लौटाता है — गणित के लिए int() या float() में लपेटें।

निष्कर्ष

Python का syntax indentation, colons और छोटे से set की constructions पर टिका है: शर्तें, for और while loops, functions, classes। इनके साथ दो दर्जन built-in functions और string, list और dictionary के methods जोड़ें — तो रोज़मर्रा के ज़्यादातर काम कवर हो जाते हैं। Cheat sheet सहेजकर रखें, और जब तालिकाएँ आदत बन जाएँ, तब modules और asynchronous programming पर जाएँ; यह सब कोर्स “Python 3.15: शुरुआती से प्रो तक” में व्यवहार में चरण-दर-चरण समझाया गया है।

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

Python में indentation के लिए कितने spaces लगाएँ?

PEP 8 के मानक के अनुसार हर स्तर पर 4 spaces। सबसे ज़रूरी बात — पूरे block में एक जैसा रहे और tabs के साथ न मिलाएँ।

list और tuple में क्या अंतर है?

List बदली जा सकती है, उसमें जोड़ सकते हैं और उसी जगह क्रमबद्ध कर सकते हैं; tuple नहीं बदलता, इसलिए वह dictionary की key बन सकता है और तय मानों के समूह के लिए ठीक है।

Python में किसी object के सारे methods कैसे देखें?

dir(obj) से नामों की सूची और help(obj) से विवरण लें — उदाहरण के लिए help(str) सभी string methods दिखाएगा।

sort() और sorted() में क्या अंतर है?

list.sort() खुद list को क्रमबद्ध करता है और None लौटाता है, जबकि sorted() नई list लौटाता है और किसी भी iterable collection पर चलता है।

क्या Python में line के अंत में semicolon चाहिए?

नहीं। एक line में कई commands के लिए semicolon चलता है, पर सामान्य code में हर statement नई line पर लिखा जाता है।