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

URL: https://skillaria.top/hi/guides/python/python-cheat-sheet

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 के अंत तक सब कुछ अनदेखा |

| Variable | `age = 25` | type घोषित नहीं होता, value से तय होता है |

| एक साथ assignment | `a, b = 1, 2` | unpacking; values की अदला-बदली: `a, b = b, a` |

| Output | `print("नमस्ते", name)` | arguments के बीच एक space |

| Input | `s = input("नाम: ")` | हमेशा string लौटाता है |

| f-string | `f"{name}: {price:.2f}"` | expressions का भीतर लगाना और format |

| Type annotation | `count: int = 0` | IDE और checkers के लिए संकेत, run के समय जाँच नहीं होती |

| खाली block | `pass` | placeholder, जहाँ syntax को body चाहिए |

| Import | `from math import sqrt` | module या उसके किसी नाम को जोड़ना |

### डेटा types

| Type | Literal | बदला जा सकता है |
| --- | --- | --- |

| `int` | `42`, `1_000_000` | नहीं |

| `float` | `3.14`, `1e-3` | नहीं |

| `bool` | `True`, `False` | नहीं |

| `str` | `"पाठ"`, `'पाठ'`, `"""कई पंक्तियाँ"""` | नहीं |

| `list` | `[1, 2, 3]` | हाँ |

| `tuple` | `(1, 2)`, `(1,)` | नहीं |

| `dict` | `{"a": 1}` | हाँ |

| `set` | `{1, 2}`, खाली — `set()` | हाँ |

| `NoneType` | `None` | — |

### Operators

| समूह | Operators | उदाहरण → नतीजा |
| --- | --- | --- |

| गणित | `+ - * / // % **` | `7 // 2` → 3, `7 % 2` → 1, `2 ** 10` → 1024 |

| तुलना | `== != < > <= >=` | `1 < x < 10` — तुलना की चेन |

| तर्क | `and or not` | `x or "डिफ़ॉल्ट"` |

| सदस्यता | `in`, `not in` | `"a" in "abc"` → True |

| पहचान | `is`, `is not` | `x 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 | क्या करता है |
| --- | --- |

| `break` | loop से समय से पहले बाहर निकलता है |

| `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 का type | `type(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()` | नई क्रमबद्ध list | `sorted(words, key=len, reverse=True)` |

| `reversed()` | उल्टे क्रम का iterator | `list(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 की पहचान और hash | `hash("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)` | पहली मौजूदगी का index | `a.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]` |

| Slices | `a[start:stop:step]` | `a[-1]` — आख़िरी, `a[:3]` — पहले तीन |

## Dictionary commands

| संक्रिया | क्या करता है | उदाहरण |
| --- | --- | --- |

| `d[key]` | key का मान; key न हो तो `KeyError` | `d["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` | नया जुड़ा हुआ dictionary | `merged = defaults | user` |

| `pop(key, default)` | हटाकर मान लौटाना | `d.pop("tmp", None)` |

| `popitem()` | आख़िरी जोड़ी हटाना | `d.popitem()` |

| `setdefault(key, value)` | मान लौटाना, और key न हो तो बनाना | `d.setdefault("tags", []).append("py")` |

| `key in d` | key मौजूद है या नहीं | `if "name" in d:` |

| `dict.fromkeys()` | एक मान वाले keys से dictionary | `dict.fromkeys("abc", 0)` |

| `len(d)`, `del d[key]` | आकार और हटाना | `del d["old"]` |

### Tuples और sets

| संक्रिया | उदाहरण → नतीजा |
| --- | --- |

| Tuple unpacking | `x, 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`, `IndentationError` | syntax या indentation में गलती |

| `NameError` | नाम परिभाषित नहीं (typo) |

| `TypeError` | गलत type पर operation: `"1" + 1` |

| `ValueError` | सही type, पर गलत मान: `int("abc")` |

| `IndexError`, `KeyError` | ऐसा index या key नहीं है |

| `FileNotFoundError` | file नहीं मिली |

| `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()` |

| `pathlib` | paths और files | `Path("data").glob("*.csv")` |

| `os`, `sys` | system, environment variables, arguments | `os.environ.get("HOME")`, `sys.argv` |

| `json` | JSON पढ़ना और लिखना | `json.loads(text)`, `json.dumps(obj, ensure_ascii=False)` |

| `csv` | CSV tables | `csv.DictReader(f)` |

| `collections` | Counter, defaultdict, deque | `Counter("banana").most_common(1)` → [('a', 3)] |

| `itertools` | iterators के combinations और chains | `itertools.chain(a, b)` |

| `re` | regular expressions | `re.findall(r"\d+", s)` |

| `time` | रुकना और समय मापना | `time.sleep(1)`, `time.perf_counter()` |

| `asyncio` | asynchronous code | `asyncio.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 --version` | version दिखाता है |

| `python3` | interactive console REPL खोलता है (बाहर — `exit()`) |

| `python3 script.py` | file चलाता है |

| `python3 -c "print(2 + 2)"` | एक line चलाता है |

| `python3 -m venv .venv` | virtual environment बनाता है |

| `source .venv/bin/activate` / `.venv\Scripts\activate` | environment चालू करता है (Linux, macOS / Windows) |

| `python3 -m pip install requests` | package install करता है |

| `pip list`, `pip freeze > requirements.txt` | packages की सूची और उसे सहेजना |

| `pip install -r requirements.txt` | file से dependencies install करता है |

| `python3 -m http.server 8000` | मौजूदा folder में सरल web server |

| `uv init`, `uv add requests`, `uv run main.py` | uv 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: शुरुआती से प्रो तक” में व्यवहार में चरण-दर-चरण समझाया गया है।

## FAQ

**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 पर लिखा जाता है।


---
Source: Skillaria.Top (https://skillaria.top)
