PALAK INFOTECH
PALAK INFOTECH PYTHON E-BOOK

Python Programming
Made Simple

पायथन प्रोग्रामिंग — आसान हिंदी में
Vinay Kumar Singh
BCA, MCA
Published by Palak Infotech
www.palakinfotech.in
पहला संस्करण · 2026

Python Programming

Palak Infotech · Computer Training Centre

1. परिचय (Introduction)

Python एक आसान और शक्तिशाली programming language है। इसका syntax अंग्रेज़ी जैसा सरल है, इसलिए शुरुआत के लिए सबसे अच्छी है। इसका इस्तेमाल web, data science, automation और AI में होता है।

Python को 1991 में Guido van Rossum ने बनाया था। इसमें हर चीज़ object होती है, number, string और function भी। इसका इस्तेमाल scripting, web (Django, Flask), data analysis (pandas), machine learning और automation में बड़े पैमाने पर होता है। Python एक general-purpose language है, यानी एक ही भाषा से कई तरह के काम होते हैं।

2. Python की विशेषताएँ

Interpreted का मतलब है कि code सीधे interpreter में चलता है, पहले exe नहीं बनता। Dynamic typing में variable का type उसकी value से तय होता है। Indentation से code का structure बनता है, इसलिए code साफ़ दिखता है। PyPI पर लाखों packages हैं, जिन्हें pip से लगाया जा सकता है।

3. Python इंस्टॉल करना

python.org से latest version download करें। Windows में installer चलाते समय Add Python to PATH ज़रूर tick करें। Check करने के लिए:

python --version

pip एक package manager है जो Python के साथ आता है, जैसे pip install requests। Virtual environment (python -m venv myenv) से हर project की libraries अलग रहती हैं। आज Python 3 ही use करें, Python 2 अब supported नहीं है।

4. IDE और IDLE

IDLE Python के साथ आता है और शुरुआत के लिए काफ़ी है। बड़े projects के लिए VS Code या PyCharm जैसे IDE use करें।

IDLE में File → New File से script बनाकर F5 से run करें। Thonny beginners के लिए सबसे आसान है। VS Code में Python extension लगाने पर autocomplete, debugging और terminal मिलते हैं। एक ही block की सारी lines बराबर indent होनी चाहिए, वरना IndentationError आता है। Python case-sensitive है, यानी Name और name दो अलग variables हैं।

5. Syntax और Indentation

Python में blocks indentation (space) से बनते हैं, curly braces से नहीं।

if 5 > 2:
    print("पाँच, दो से बड़ा है")

Comments Python ignore करता है, ये सिर्फ़ समझाने के लिए हैं। अच्छा comment बताता है क्यों code लिखा गया, सिर्फ़ क्या हो रहा है वो नहीं। Function के पहले लिखी docstring help() में दिखती है।

def add(a, b):
    """दो नंबर जोड़ता है"""
    return a + b

6. Comments

# यह एक line comment है
"""
यह multi-line comment है
"""
print("नमस्ते")  # line के अंत में comment

Keywords जैसे if, for, class, def, return, True, None reserved हैं। list या str keyword नहीं हैं, ये built-in names हैं, इन्हें variable बनाना बुरी आदत है। Variable का नाम अक्षर या _ से शुरू हो, बीच में space न हो। अच्छा तरीका snake_case है, जैसे total_marks।

7. Keywords

ये Python के reserved words हैं। इन्हें variable का नाम नहीं बना सकते।

import keyword
print(keyword.kwlist)

Variable एक नाम है जो memory में रखी value की तरफ़ इशारा करता है। x = 5 के बाद x = "hi" भी valid है, इसे dynamic typing कहते हैं। id() से memory address देख सकते हैं। Constants की पहचान UPPERCASE नाम से होती है, जैसे PI = 3.14।

8. Variables

naam = "Ravi"
umar = 20
a, b = 5, 10
x = y = 0
print(naam, umar, a, b)

int की कोई सीमा नहीं होती, बहुत बड़े नंबर भी चलते हैं। float में precision सीमित है, इसलिए 0.1 + 0.2 ठीक 0.3 नहीं देता। None का मतलब है कोई value नहीं। bool के True और False को numbers में 1 और 0 माना जाता है।

9. Data Types

Typeउदाहरणमतलब
int10पूरे नंबर
float3.14दशमलव नंबर
str"Hello"Text
boolTrueसही या गलत
list[1, 2]बदला जा सकता है
tuple(1, 2)बदला नहीं जा सकता
set{1, 2}सिर्फ़ unique values
dict{"a": 1}key-value pairs
print(type(10))
print(type(3.5))
print(type("hi"))
print(type(True))

Implicit conversion Python खुद करता है: 5 + 2.0 देगा 7.0। Explicit conversion आप करते हैं। गलत conversion पर ValueError आता है, जैसे int("abc")। int(3.9) decimal हटा देता है, round नहीं करता।

10. Type Conversion

print(int("25") + 5)     # 30
print(float("2.5"))      # 2.5
print(str(100) + "A")    # 100A
print(int(3.9))          # 3
print(list("abc"))       # ['a', 'b', 'c']

input() हमेशा string देता है, इसलिए input("...") + 5 error देगा। print() में sep और end से format बदलते हैं। आज का सबसे साफ़ तरीका f-string है: print(f"नाम {naam}")।

11. Input और Output

input() हमेशा string देता है, इसलिए number चाहिए तो convert करें।

naam = input("नाम बताओ: ")
umar = int(input("उम्र बताओ: "))
print("नमस्ते", naam, "उम्र:", umar)
print("A", "B", sep="-")       # A-B

Division हमेशा float देता है। Floor division नीचे की तरफ़ गोल करता है, इसलिए negative में परिणाम -4 आता है। Modulus से even/odd और divisibility check होती है।

print(7 / 2)    # 3.5
print(7 // 2)   # 3
print(-7 // 2)  # -4
print(7 % 3)    # 1
print(2 ** 10)  # 1024

12. Arithmetic Operators

Operatorमतलबa=10, b=3
+ - * /जोड़, घटाना, गुणा, भाग13, 7, 30, 3.33
//Floor division3
%बाकी (modulus)1
**घात (power)1000

Comparison का परिणाम हमेशा bool होता है। Strings की तुलना dictionary order में होती है, जैसे "apple" < "banana" True है। Chaining भी चलती है: 1 < x < 10।

13. Comparison Operators

a, b = 10, 3
print(a == b)   # False
print(a != b)   # True
print(a > b)    # True
print(a <= 9)   # False

and तभी True है जब दोनों True हों। or तब True है जब एक भी True हो। Python short-circuit करता है: False and कुछ भी तुरंत False देता है। असली उदाहरण: if age >= 18 and has_id:।

14. Logical Operators

x = 5
print(x > 0 and x < 10)   # True
print(x > 0 or x > 100)   # True
print(not(x > 0))         # False

+= जैसे operators variable को update करते हैं, नया variable नहीं बनाते। x = x + 1 और x += 1 एक जैसे हैं। Counter और total बनाने में यही सबसे ज़्यादा इस्तेमाल होता है।

15. Assignment Operators

x = 10
x += 5    # 15
x -= 3    # 12
x *= 2    # 24
x //= 5   # 4
x **= 2   # 16
print(x)

Dictionary में in सिर्फ़ keys check करता है, values नहीं। String में in substring check करता है। बहुत बड़ी list में in धीमा होता है, वहाँ set ज़्यादा तेज़ है।

16. Membership Operators

fruits = ["apple", "banana"]
print("apple" in fruits)       # True
print("mango" not in fruits)   # True

is memory में object check करता है, value नहीं। Small integers (लगभग -5 से 256) cache होते हैं, इसलिए ऐसे नंबरों पर is अक्सर True देता है, पर यह गारंटी नहीं है। Value की तुलना के लिए == use करें। None check के लिए is None standard तरीका है।

17. Identity Operators

is check करता है कि दोनों एक ही object हैं या नहीं।

a = [1, 2]
b = [1, 2]
c = a
print(a == b)   # True  (value same)
print(a is b)   # False (अलग objects)
print(a is c)   # True  (वही object)

Condition में खाली list, 0, "" और None False माने जाते हैं। बाकी लगभग सब True। if एक बार में सिर्फ़ पहला सही branch चलाता है, इसलिए शर्तों का क्रम महत्वपूर्ण है। बड़ी शर्त को पहले और खास शर्त को बाद में रखें।

18. if, elif और else

marks = int(input("Marks: "))

if marks >= 90:
    print("Grade A")
elif marks >= 60:
    print("Grade B")
elif marks >= 35:
    print("Grade C")
else:
    print("Fail")

Nested if तभी use करें जब दूसरी शर्त सच में पहली पर निर्भर हो। बहुत गहराई होने पर and से combine करें। Early return का पैटर्न code को साफ़ रखता है।

19. Nested If

age = int(input("Age: "))
if age >= 18:
    if age >= 60:
        print("Senior citizen")
    else:
        print("Adult")
else:
    print("Minor")

range(start, stop, step) में stop शामिल नहीं होता। range memory में पूरी list नहीं बनाता, इसलिए बड़ी सीमा भी तेज़ चलती है। enumerate() से index और value दोनों मिलते हैं। Loop के बाद भी variable आख़िरी value रखता है।

fruits = ["आम", "केला"]
for i, f in enumerate(fruits, 1):
    print(i, f)   # 1 आम, 2 केला

20. for Loop

for i in range(5):          # 0 से 4
    print(i)

for i in range(1, 11, 2):   # 1 3 5 7 9
    print(i)

for ch in "Python":
    print(ch)

while तब तक चलता है जब तक शर्त True हो। अगर शर्त कभी False न हो तो infinite loop बन जाता है। Input validation के लिए while True और break का पैटर्न बहुत उपयोगी है।

21. while Loop

count = 1
while count <= 5:
    print(count)
    count += 1

break सिर्फ़ सबसे अंदर वाला loop रोकता है। continue बाकी code skip करके अगले iteration पर जाता है। pass खाली block रखने के लिए है। Loop के साथ else भी हो सकता है, जो तभी चलता है जब loop बिना break के पूरा खत्म हो।

22. break, continue और pass

for i in range(1, 10):
    if i == 5:
        break        # loop यहीं बंद
    print(i)         # 1 2 3 4

for i in range(1, 6):
    if i == 3:
        continue     # 3 को skip
    print(i)         # 1 2 4 5

for i in range(3):
    pass             # बाद में code लिखने के लिए placeholder

String immutable है, यानी s[0] = "x" error देगा, नया string बनाना पड़ता है। Triple quotes multi-line string देते हैं। Escape sequences: \n नई line, \t tab। f-string में variables सीधे डाले जाते हैं।

23. Strings

s = "Hello Python"
print(len(s))        # 12
print(s.upper())     # HELLO PYTHON
print(s + "!")       # Hello Python!
print(s * 2)

Index 0 से शुरू होता है। Out of range index पर IndexError आता है। Slicing में stop शामिल नहीं होता। s[::-1] पूरा string उलटता है, जो palindrome check में काम आता है।

24. String Indexing और Slicing

s = "PYTHON"
print(s[0])      # P
print(s[-1])     # N
print(s[0:3])    # PYT
print(s[2:])     # THON
print(s[::-1])   # NOHTYP

String methods मूल string नहीं बदलते, नया return करते हैं। strip() दोनों तरफ़ से spaces हटाता है, lstrip() और rstrip() एक तरफ़ से। split(",") string को list बनाता है, और ",".join(list) उल्टा करता है। Validation के लिए isdigit() और isalpha() काम आते हैं।

25. String Methods

s = "  hello python  "
print(s.strip())                  # साफ़ करना
print(s.title())
print(s.replace("python", "world"))
print(s.split())                  # ['hello', 'python']
print(",".join(["a", "b"]))       # a,b
print(s.find("python"))
print(s.count("l"))

List में अलग-अलग types मिल सकते हैं। Nested list से दो-आयामी data बनता है। List को दूसरी variable में assign करने से दोनों एक ही list होती हैं। असली copy के लिए .copy() या list(x) use करें।

matrix = [[1, 2], [3, 4]]
print(matrix[1][0])   # 3
a = [1, 2]
b = a.copy()          # अलग copy

26. Lists

List एक ordered और बदली जा सकने वाली collection है। यही Python का array है।

fruits = ["apple", "banana", "mango"]
print(fruits[0])     # apple
print(fruits[-1])    # mango
fruits[1] = "kiwi"
print(len(fruits))

append एक item जोड़ता है, extend कई। append([1, 2]) list को एक item की तरह जोड़ता है, जबकि extend([1, 2]) दो items जोड़ता है। sort() मूल list बदलता है, sorted() नई बनाता है।

nums = [3, 1, 2]
nums.sort(reverse=True)
print(nums)   # [3, 2, 1]

27. List Methods

nums = [5, 2, 8]
nums.append(10)       # आख़िर में जोड़ो
nums.insert(1, 7)     # index 1 पर
nums.extend([1, 3])   # दूसरी list जोड़ो
nums.remove(7)        # value हटाओ
nums.pop()            # आख़िरी item हटाओ
nums.sort()
nums.reverse()
print(nums.index(8))
print(nums.count(2))
nums.clear()

Tuple fixed data के लिए सुरक्षित है और dictionary की key बन सकता है। Function से कई values return करने के लिए tuple use होता है, और unpacking से उन्हें अलग variables में लिया जाता है।

def minmax(nums):
    return min(nums), max(nums)

lo, hi = minmax([4, 9, 1])
print(lo, hi)   # 1 9

List के सारे Methods और Functions: पूरा उदाहरण

नीचे दिए example में हर method एक के बाद एक चलता है। टिप्पणी में list की हालत लिखी है।

nums = [5, 2, 8]
nums.append(10)        # [5, 2, 8, 10]
nums.extend([1, 3])    # [5, 2, 8, 10, 1, 3]
nums.insert(0, 9)      # [9, 5, 2, 8, 10, 1, 3]
nums.remove(5)         # [9, 2, 8, 10, 1, 3]
last = nums.pop()      # last = 3, nums = [9, 2, 8, 10, 1]
print(nums.index(8))   # 2
print(nums.count(2))   # 1
nums.sort()            # [1, 2, 8, 9, 10]
nums.reverse()         # [10, 9, 8, 2, 1]
backup = nums.copy()   # alag copy
nums.clear()           # []
print(backup)          # [10, 9, 8, 2, 1]

अब list के साथ इस्तेमाल होने वाले built-in functions:

marks = [45, 78, 62, 91]
names = ["Ravi", "Amit", "Sita", "Priya"]

print(len(marks))                  # 4
print(sum(marks))                  # 276
print(min(marks), max(marks))      # 45 91
print(sorted(marks))               # [45, 62, 78, 91] (marks नहीं बदलती)
print(list("abc"))                 # ['a', 'b', 'c']
print(any(m > 90 for m in marks))  # True (कोई एक)
print(all(m > 40 for m in marks))  # True (सब)

for i, m in enumerate(marks, 1):   # index और value
    print(i, m)

print(list(reversed(marks)))       # [91, 62, 78, 45]

for n, m in zip(names, marks):     # दो lists जोड़ना
    print(n, m)

print(list(map(lambda m: m + 5, marks)))     # [50, 83, 67, 96]
print(list(filter(lambda m: m >= 60, marks))) # [78, 62, 91]

28. Tuples

Tuple, list जैसा है लेकिन इसे बदला नहीं जा सकता। इसमें round brackets () होते हैं।

t = (10, 20, 30, 20)
print(t[0])          # 10
print(t.count(20))   # 2
single = (5,)        # एक item के लिए comma ज़रूरी

Set में list जैसे mutable items नहीं रख सकते। Duplicate हटाने का सबसे आसान तरीका है set(list_data)। Empty set set() से बनता है, {} dictionary होता है।

29. Sets

Set में सिर्फ़ unique values होती हैं और order तय नहीं होता।

s = {1, 2, 3, 3, 2}
print(s)              # {1, 2, 3}
s.add(4)
s.discard(10)         # error नहीं देगा
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)          # union
print(a & b)          # intersection
print(a - b)          # difference

Key unique और immutable होनी चाहिए (string, number, tuple)। Duplicate key आए तो आख़िरी value रहती है। d["x"] missing key पर KeyError देता है, जबकि d.get("x") None देता है। Dictionary के अंदर dictionary भी रख सकते हैं।

students = {"Ravi": {"marks": 85}, "Amit": {"marks": 72}}
print(students["Ravi"]["marks"])   # 85

30. Dictionary

Dictionary में key: value pairs होते हैं।

student = {"name": "Ravi", "age": 20}
print(student["name"])       # Ravi
print(student.get("age"))    # 20
student["marks"] = 85        # नया key जोड़ा
print(student)

items() loop में key और value दोनों देता है। setdefault(key, default) key न हो तो default डालता है। update() एक dictionary को दूसरी से merge करता है। Counting के लिए यह पैटर्न आम है:

counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)   # {'b': 1, 'a': 3, 'n': 2}

31. Dictionary Methods

d = {"a": 1, "b": 2}
print(d.keys())
print(d.values())
print(d.items())
d.update({"c": 3})
print(d.pop("a"))        # 1
print(d.get("z", 0))     # 0 (default)
for k, v in d.items():
    print(k, v)

Function बार-बार इस्तेमाल होने वाले code को एक नाम देता है। Function तभी चलता है जब उसे call किया जाए। Function के अंदर बने variables बाहर नहीं दिखते, इसे local scope कहते हैं।

32. Functions

def greet(naam):
    print("नमस्ते,", naam)

greet("Ravi")

Positional arguments का क्रम मायने रखता है। Keyword arguments से क्रम बदल सकता है। Default values हमेशा आख़िर में होनी चाहिए। *args tuple बनाता है और **kwargs dictionary, जिससे function में लचीलापन आता है।

33. Function Arguments

def add(a, b):
    return a + b
print(add(2, 3))              # 5

def info(naam, umar):
    print(naam, umar)
info(umar=20, naam="Ravi")    # keyword argument

def hello(naam="Guest"):      # default value
    print("Hi", naam)
hello()

def total(*nums):             # *args
    return sum(nums)
print(total(1, 2, 3))         # 6

def show(**data):             # **kwargs
    print(data)
show(city="Patna", age=20)

बिना return के function None देता है। return के बाद का code नहीं चलता। print सिर्फ़ screen पर दिखाता है, जबकि return value को आगे इस्तेमाल करने देता है।

34. Return Statement

def square(n):
    return n * n

print(square(4))   # 16

Lambda में सिर्फ़ एक expression हो सकता है। Sorting में key के रूप में यह बहुत काम आता है। जटिल logic के लिए normal def बेहतर है।

students = [("Ravi", 85), ("Amit", 72)]
students.sort(key=lambda s: s[1])
print(students)   # [('Amit', 72), ('Ravi', 85)]

35. Lambda Functions

Lambda एक छोटा, एक line वाला function है जिसका नाम नहीं होता।

square = lambda x: x * x
print(square(5))                                  # 25
nums = [1, 2, 3, 4, 5, 6]
print(list(filter(lambda n: n % 2 == 0, nums)))   # [2, 4, 6]
print(list(map(lambda n: n * 2, nums)))           # [2, 4, ...]

हर recursive call problem को छोटा करता है और base case पर रुकता है। Base case न हो या recursion बहुत गहरी हो तो error आता है। Fibonacci में recursion साफ़ दिखती है, पर बड़े n के लिए loop तेज़ होता है।

36. Recursion

जब function खुद को call करे। Base case ज़रूरी है, वरना loop कभी खत्म नहीं होगा।

def factorial(n):
    if n == 0:          # base case
        return 1
    return n * factorial(n - 1)

print(factorial(5))     # 120

import module पूरा module लाता है, जबकि from module import name सिर्फ़ वही हिस्सा। अपनी file mycalc.py बनाकर उसे दूसरी file में import कर सकते हैं। if __name__ == "__main__": के अंदर का code तभी चलता है जब file सीधे run हो।

37. Modules

import math
from math import sqrt
import random as r

print(math.pi)
print(sqrt(16))         # 4.0
print(r.randint(1, 6))

Built-in functions को import की ज़रूरत नहीं होती। help(len) से किसी भी function की जानकारी मिलती है। map, filter और zip lazy होते हैं, यानी list() में लपेटने पर ही values बनती हैं।

38. Built-in Functions

Functionकाम
print()Output दिखाना
input()User से input लेना
len()लंबाई / गिनती
type()Data type बताना
range()नंबरों की sequence
sum(), min(), max()जोड़, सबसे छोटा, सबसे बड़ा
abs(), round()Absolute value, गोल करना
sorted()Sort करके नई list
enumerate()Index और value दोनों
zip()दो lists को जोड़ना
print(max(3, 9))              # 9
print(round(3.678, 1))        # 3.7
print(list(enumerate(["a", "b"])))

math.pow हमेशा float देता है, जबकि ** int भी देता है। math.isqrt(n) integer square root देता है। math.inf और math.nan भी उपलब्ध हैं।

39. Math Module

import math
print(math.sqrt(49))      # 7.0
print(math.floor(4.7))    # 4
print(math.ceil(4.1))     # 5
print(math.factorial(5))  # 120
print(math.gcd(12, 18))   # 6

random.seed(42) से हर बार वही random sequence आती है, testing में यह उपयोगी है। randint(a, b) में दोनों सीमाएँ शामिल हैं। Game और quiz में choice और shuffle बहुत काम आते हैं।

40. Random Module

import random
print(random.randint(1, 10))
print(random.random())
colors = ["red", "green", "blue"]
print(random.choice(colors))
random.shuffle(colors)

strptime string को date में बदलता है, और timedelta दो तारीखों का फ़र्क देता है। weekday() में 0 मतलब सोमवार। %I:%M %p से 12 घंटे का समय मिलता है।

from datetime import datetime
d = datetime.strptime("2026-01-15", "%Y-%m-%d")
print(d.strftime("%d %B %Y"))   # 15 January 2026

41. Date और Time

from datetime import datetime, date, timedelta

now = datetime.now()
print(now.strftime("%d-%m-%Y %H:%M"))
today = date.today()
print("कल:", today + timedelta(days=1))

%d दिन, %m महीना, %Y साल, %H घंटा, %M मिनट

Error के type के हिसाब से except लिखें, सब कुछ एक साथ पकड़ना बुरी आदत है। raise से खुद error फेंक सकते हैं। else तभी चलता है जब try में कोई error न हो।

def set_age(age):
    if age < 0:
        raise ValueError("उम्र ऋणात्मक नहीं हो सकती")
    return age

42. Exception Handling

try:
    num = int(input("Number: "))
    print(10 / num)
except ValueError:
    print("सिर्फ़ number लिखो")
except ZeroDivisionError:
    print("Zero से divide नहीं हो सकता")
finally:
    print("यह हमेशा चलेगा")

गलत path पर FileNotFoundError आता है। Read mode में file न हो तो error आता है, जबकि write mode नई file बना देता है। with file को अपने आप बंद करता है, भले ही बीच में error आए।

43. File Handling

फ़ाइल पढ़ना और लिखना

Modes: "r" पढ़ने के लिए, "w" लिखने के लिए (पुराना data मिटता है), "a" जोड़ने के लिए।

# लिखना
with open("data.txt", "w") as f:
    f.write("Hello file\n")

# जोड़ना
with open("data.txt", "a") as f:
    f.write("नई line\n")

# पढ़ना
with open("data.txt", "r") as f:
    print(f.read())

Comprehension में if-else भी हो सकता है। Dictionary और set comprehension भी होते हैं। बहुत लंबी comprehension समझने में मुश्किल होती है, तब normal loop बेहतर है।

44. List Comprehension

squares = [i * i for i in range(1, 6)]
print(squares)                 # [1, 4, 9, 16, 25]
evens = [n for n in range(10) if n % 2 == 0]
print(evens)                   # [0, 2, 4, 6, 8]

OOP से बड़ा program व्यवस्थित रहता है। Real-world चीज़ें जैसे Student, Car या Account को code में model किया जाता है। Class का नाम आम तौर पर हर शब्द के पहले अक्षर से बड़े अक्षर में लिखा जाता है, जैसे BankAccount।

45. OOP के मूल सिद्धांत

self उस object को दर्शाता है जिस पर method call हुआ है। Class variable सभी objects में साझा होता है, जबकि instance variable हर object का अलग होता है। isinstance(s1, Student) check करता है कि object किस class का है।

46. Classes और Objects

class Student:
    def __init__(self, naam, umar):
        self.naam = naam
        self.umar = umar

    def display(self):
        print("नाम:", self.naam, "उम्र:", self.umar)

s1 = Student("Ravi", 20)
s1.display()

Constructor में default values, validation और ज़रूरी setup रखा जाता है। __str__ method object को readable text देता है, जो print() में दिखता है।

class Student:
    def __init__(self, naam):
        self.naam = naam
    def __str__(self):
        return f"छात्र: {self.naam}"

print(Student("Ravi"))   # छात्र: Ravi

47. Constructor

__init__ object बनते ही अपने आप चलता है।

class Car:
    def __init__(self, brand, price=500000):
        self.brand = brand
        self.price = price

c1 = Car("Maruti")
c2 = Car("Honda", 900000)
print(c1.price, c2.price)

super().__init__() से parent का constructor call होता है। Method override करने पर भी parent का version super().method() से लिया जा सकता है। Inheritance "is-a" संबंध के लिए है: Dog एक Animal है।

48. Inheritance

class Animal:
    def __init__(self, naam):
        self.naam = naam

    def speak(self):
        print(self.naam, "आवाज़ निकालता है")

class Dog(Animal):           # Animal से inherit
    pass

Dog("Tommy").speak()

Example: Palak Infotech के नाम से code

नीचे के examples में string, list, loop और class सब एक ही संस्था के नाम पर समझाए गए हैं।

company = "Palak Infotech"
print("Welcome to", company)
print(company.upper())             # PALAK INFOTECH
print(len(company))                # 14
print(company[0:6])                # Palak
print(company.split())             # ['Palak', 'Infotech']

courses = ["Python", "Tally", "GST"]
for c in courses:
    print(company, "-", c, "course")

class Institute:
    def __init__(self, name):
        self.name = name

    def info(self):
        return f"{self.name} | www.palakinfotech.in"

print(Institute("Palak Infotech").info())

49. Mini Projects

Project 1: Calculator

a = float(input("पहला नंबर: "))
b = float(input("दूसरा नंबर: "))
op = input("Operator (+ - * /): ")

if op == "+":
    print(a + b)
elif op == "-":
    print(a - b)
elif op == "*":
    print(a * b)
elif op == "/" and b != 0:
    print(a / b)
else:
    print("गलत input")

Project 2: नंबर गेस गेम

import random

secret = random.randint(1, 20)
attempts = 0
while True:
    guess = int(input("अनुमान लगाओ (1-20): "))
    attempts += 1
    if guess < secret:
        print("बड़ा नंबर सोचो")
    elif guess > secret:
        print("छोटा नंबर सोचो")
    else:
        print("सही! कोशिशें:", attempts)
        break

Project 3: To-Do List

tasks = []
while True:
    print("\n1. जोड़ो  2. दिखाओ  3. बंद करो")
    choice = input("चुनो: ")
    if choice == "1":
        tasks.append(input("Task: "))
    elif choice == "2":
        for i, t in enumerate(tasks, 1):
            print(i, t)
    elif choice == "3":
        break

Project 4: Bank Account (OOP)

class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amt):
        self.balance += amt

    def withdraw(self, amt):
        if amt <= self.balance:
            self.balance -= amt
        else:
            print("बैलेंस कम है")

acc = Account("Ravi", 1000)
acc.deposit(500)
acc.withdraw(200)
print(acc.balance)   # 1300

हर project को छोटे हिस्सों में लिखें: पहले input, फिर logic, फिर output। Errors आएँ तो try-except लगाएँ। अगला कदम: Calculator में division by zero handle करें, To-Do List में tasks को file में save करें।

✏️ PALAK INFOTECH PYTHON E-BOOK · Vinay Kumar Singh (BCA, MCA) · www.palakinfotech.in