آموزش برنامه‌نویسی پایتون و هوش مصنوعی
140 subscribers
358 photos
190 videos
41 files
172 links
🎯 یادگیری پایتون با رویکردی متفاوت
🚀 آموزش‌های کاملاً عملی و پروژه‌محور
💻 مسیر تبدیل شدن به یک برنامه‌نویس حرفه‌ای
🌟 فرقی نداره مبتدی هستی یا پیشرفته، از هر سطحی شروع کن و پایتون رو اصولی یاد بگیر
📩 ارتباط با ادمین: @YMahmoodian
09156519984
Download Telegram
سوال ۷۳ – حلقه for با شرط و جمع مقادیر زوج لیست

nums = [1, 2, 3, 4, 5, 6]
total = 0
for n in nums:
if n % 2 == 0:
total += n
print(total)

جواب:

12

توضیح:

حلقه for روی لیست nums می‌چرخد.

شرط if n % 2 == 0 مقادیر زوج را انتخاب می‌کند.

این مقادیر به متغیر total اضافه می‌شوند.

جمع اعداد زوج 2 + 4 + 6 = 12 است.






74. حلقه for روی لیست اعداد



nums = [1,2,3,4]
for n in nums:
print(n*2)

جواب: 2 4 6 8

75. حلقه while روی لیست



nums=[1,2,3]
i=0
while i<len(nums):
print(nums[i]+1)
i+=1

جواب: 2 3 4

76. حلقه for روی رشته و چاپ حروف بزرگ



s = "python"
for ch in s:
print(ch.upper())

جواب: P Y T H O N

77. حلقه while روی رشته و چاپ حروف غیر تکراری



s="hello"
i=0
seen=[]
while i<len(s):
if s[i] not in seen:
print(s[i])
seen.append(s[i])
i+=1

جواب: h e l o

78. حلقه for روی دیکشنری و چاپ کلیدهای بزرگ



d = {'a':1,'b':2}
for k in d.keys():
print(k.upper())

جواب: A B

79. حلقه for روی دیکشنری و مقادیر چند برابر



d={'x':2,'y':5}
for v in d.values():
print(v*10)

جواب: 20 50

80. حلقه for روی مجموعه با شرط



s={1,2,3,4}
for n in s:
if n%2==0:
print(n)

جواب: 2 4

81. حلقه while با شمارنده و break



i=0
while i<10:
if i==6:
break
print(i)
i+=2

جواب: 0 2 4

82. حلقه while با continue



i=0
while i<5:
i+=1
if i==3:
continue
print(i)

جواب: 1 2 4 5

83. حلقه for با enumerate روی رشته



s="abc"
for idx,ch in enumerate(s):
print(idx,ch)

جواب: 0 a 1 b 2 c

84. حلقه for با enumerate روی لیست



lst=[10,20,30]
for idx,val in enumerate(lst):
print(idx,val*2)

جواب: 0 20 1 40 2 60

85. حلقه for با zip دو لیست



a=[1,2,3]
b=[4,5,6]
for x,y in zip(a,b):
print(x+y)

جواب: 5 7 9

86. حلقه for روی رشته با شرط حروف صدادار



s="python"
for ch in s:
if ch in 'aeiou':
print(ch)

جواب: o

87. حلقه while با شمارش تعداد حروف



s="hello"
i=0
count=0
while i<len(s):
count+=1
i+=1
print(count)

جواب: 5

88. حلقه for با شرط و break روی لیست



nums=[1,3,5,4,6]
for n in nums:
if n%2==0:
print(n)
break

جواب: 4

89. حلقه for با شرط و continue روی لیست



nums=[1,2,3,4]
for n in nums:
if n%2!=0:
continue
print(n)

جواب: 2 4

90. حلقه تو در تو برای جمع ماتریس 2x2



matrix=[[1,2],[3,4]]
for row in matrix:
for val in row:
print(val)

جواب: 1 2 3 4

91. حلقه for روی لیست با شرط و else



nums=[1,2,3]
for n in nums:
print(n)
else:
print("Done")

جواب: 1 2 3 Done

92. حلقه while با شمارنده و else



i=0
while i<3:
print(i)
i+=1
else:
print("Finished")

جواب: 0 1 2 Finished

93. حلقه for روی رشته و skip حروف کوچک



s="PyThoN"
for ch in s:
if ch.islower():
continue
print(ch)

جواب: P T N

94. حلقه for روی رشته و stop روی حرف N



s="Python"
for ch in s:
if ch=="N":
break
print(ch)

جواب: P y t h o

95. حلقه while برای کاهش شمارنده تا صفر



i=5
while i>0:
print(i)
i-=1

جواب: 5 4 3 2 1

96. حلقه for با range معکوس



for i in range(5,0,-1):
print(i)

جواب: 5 4 3 2 1

97. حلقه while با شرط ترکیبی



i=0
while i<10 and i!=7:
print(i)
i+=2

جواب: 0 2 4 6

98. حلقه for روی رشته با index



s="abc"
for i in range(len(s)):
print(i,s[i])

جواب: 0 a 1 b 2 c

99. حلقه for روی دیکشنری و break



d={'a':1,'b':2}
for k,v in d.items():
if v==2:
break
print(k,v)

جواب: a 1

100. حلقه while با continue و شمارنده



i=0
while i<5:
i+=1
if i==3:
continue
print(i)

جواب: 1 2 4 5


---
بخش ۳: پیشرفته‌تر روی توابع (سوال 41–60)

41. تابع با آرگومان mutable و اثر آن بیرون



def add_item(lst):
lst.append(10)
mylist = [1,2]
add_item(mylist)
print(mylist)

جواب: [1,2,10]
توضیح: لیست mutable است و تغییرات داخل تابع روی لیست اصلی اعمال می‌شود.

42. تابع با آرگومان immutable



def increment(x):
x += 1
return x
num = 5
print(increment(num))
print(num)

جواب:

6
5

توضیح: عدد immutable است، مقدار اصلی تغییر نمی‌کند.

43. تابع با آرگومان string و تغییر آن



def add_text(s):
s += " world"
return s
txt = "Hello"
print(add_text(txt))
print(txt)

جواب:

Hello world
Hello

44. تابع با بازگشت چند نوع داده



def get_data():
return 1, "Ali", [1,2,3]
a,b,c = get_data()
print(a,b,c)

جواب: 1 Ali [1,2,3]

45. تابع با شرط و raise خطا



def check_positive(x):
if x<0:
raise ValueError("Negative!")
return x
print(check_positive(5))

جواب: 5

46. تابع بازگشتی ساده



def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
print(factorial(5))

جواب: 120

47. تابع بازگشتی با شرط پیچیده



def fibonacci(n):
if n<=1:
return n
return fibonacci(n-1)+fibonacci(n-2)
print(fibonacci(6))

جواب: 8

48. تابع lambda ساده



f = lambda x: x*3
print(f(4))

جواب: 12

49. تابع lambda با چند آرگومان



f = lambda x,y: x+y
print(f(5,7))

جواب: 12

50. تابع lambda داخل تابع دیگر



def make_multiplier(n):
return lambda x: x*n
double = make_multiplier(2)
print(double(5))

جواب: 10

51. تابع با map و lambda



nums = [1,2,3]
result = list(map(lambda x: x**2, nums))
print(result)

جواب: [1,4,9]

52. تابع با filter و lambda



nums = [1,2,3,4]
evens = list(filter(lambda x: x%2==0, nums))
print(evens)

جواب: [2,4]

53. تابع با reduce (import functools)



from functools import reduce
nums = [1,2,3,4]
total = reduce(lambda x,y: x+y, nums)
print(total)

جواب: 10

54. تابع با list comprehension داخل تابع



def square_list(lst):
return [x**2 for x in lst]
print(square_list([1,2,3]))

جواب: [1,4,9]

55. تابع با شرط داخل list comprehension



def evens(lst):
return [x for x in lst if x%2==0]
print(evens([1,2,3,4,5]))

جواب: [2,4]

56. تابع با enumerate در list comprehension



def even_index(lst):
return [v for i,v in enumerate(lst) if i%2==0]
print(even_index([10,20,30,40]))

جواب: [10,30]

57. تابع با zip



names = ["Ali","Sara"]
ages = [25,30]
for n,a in zip(names,ages):
print(n,a)

جواب:

Ali 25
Sara 30

58. تابع با unpacking آرایه در آرگومان



def add(a,b,c):
return a+b+c
nums = [1,2,3]
print(add(*nums))

جواب: 6

59. تابع با unpacking dict در آرگومان



def describe(name, age):
print(name, age)
info = {"name":"Ali","age":25}
describe(**info)

جواب: Ali 25

60. تابع با decorator ساده



def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@decorator
def say_hello():
print("Hello")
say_hello()

جواب:

Before
Hello
After


---
بخش ۴: پیشرفته – ترکیب مفاهیم و سناریوهای پیچیده (سوال 61–80)
61. تابع بازگشتی با شرط توقف غیرساده
def countdown(n): print(n) if n > 0: countdown(n-1) countdown(3)
جواب:
3 2 1 0
62. تابع بازگشتی معکوس رشته
def reverse(s): if s == "": return "" return reverse(s[1:]) + s[0] print(reverse("abc"))
جواب:
cba
63. تابع با default parameter
def greet(name="Guest"): print("Hello", name) greet() greet("Ali")
جواب:
Hello Guest Hello Ali
64. پارامتر پیش‌فرض mutable (خطرناک!)
def add_num(num, lst=[]): lst.append(num) return lst print(add_num(1)) print(add_num(2))
جواب:
[1] [1, 2]
توضیح: لیست پیش‌فرض بین فراخوانی‌ها مشترک است.
65. جلوگیری از مشکل بالا
def add_num(num, lst=None): if lst is None: lst = [] lst.append(num) return lst print(add_num(1)) print(add_num(2))
جواب:
[1] [2]
*66. تابع با args
def total(*numbers): return sum(numbers) print(total(1,2,3))
جواب: 6
**67. تابع با kwargs
def info(**data): for k,v in data.items(): print(k, v) info(name="Ali", age=25)
جواب:
name Ali age 25
**68. ترکیب *args و kwargs
def func(*args, **kwargs): print(args) print(kwargs) func(1,2, name="Ali", age=25)
جواب:
(1, 2) {'name': 'Ali', 'age': 25}
69. تابع بازگشتی جمع لیست
def sum_list(lst): if not lst: return 0 return lst[0] + sum_list(lst[1:]) print(sum_list([1,2,3]))
جواب: 6
70. تابع بازگشتی حداکثر در لیست
def max_list(lst): if len(lst) == 1: return lst[0] m = max_list(lst[1:]) return m if m > lst[0] else lst[0] print(max_list([1,9,3]))
جواب: 9
71. تابع بازگشتی بررسی palindrome
def is_palindrome(s): if len(s) <= 1: return True return s[0] == s[-1] and is_palindrome(s[1:-1]) print(is_palindrome("madam"))
جواب: True
72. تابع با inner function
def outer(): def inner(): print("Hello from inner") inner() outer()
جواب:
Hello from inner
73. تابع که تابع برمی‌گرداند
def make_adder(n): def adder(x): return x + n return adder add5 = make_adder(5) print(add5(10))
جواب: 15
74. closure با شمارنده
def counter(): count = 0 def inc(): nonlocal count count += 1 return count return inc c = counter() print(c()) print(c())
جواب:
1 2
75. تابع generator ساده
def gen_numbers(): yield 1 yield 2 yield 3 for n in gen_numbers(): print(n)
جواب:
1 2 3
76. generator با شرط
def even_gen(n): for i in range(n): if i % 2 == 0: yield i print(list(even_gen(6)))
جواب: [0, 2, 4]
77. استفاده از yield from
def sub_gen(): yield 1 yield 2 def main_gen(): yield from sub_gen() yield 3 print(list(main_gen()))
جواب: [1, 2, 3]
78. تابع با annotation نوع داده
def add(x: int, y: int) -> int: return x + y print(add(2,3))
جواب: 5
79. تابع با docstring
def greet(): """این تابع سلام می‌کند.""" print("Hello") print(greet.__doc__)
جواب:
این تابع سلام می‌کند.
80. تابع با بازگشت تابع ناشناس
def power(n): return lambda x: x**n square = power(2) print(square(5))
جواب: 25
بخش ۵: پیشرفته – سناریوهای خاص و نکات حرفه‌ای (سوال 81–100)

81. تابع بازگشتی برای شمارش عناصر لیست چندلایه

def count_elements(lst):
total = 0
for i in lst:
if isinstance(i, list):
total += count_elements(i)
else:
total += 1
return total
print(count_elements([1,[2,3],[4,[5]]]))

جواب: 5


---

82. تابع با تابع کمکی (helper) داخلی

def factorial(n):
def helper(x):
if x == 0:
return 1
return x * helper(x-1)
return helper(n)
print(factorial(4))

جواب: 24


---

83. تابع که از global استفاده می‌کند

count = 0
def inc():
global count
count += 1
inc()
inc()
print(count)

جواب: 2


---

84. تابع با keyword-only arguments

def greet(*, name):
print("Hello", name)
greet(name="Sara")

جواب: Hello Sara


---

85. تابع با positional-only arguments (Python 3.8+)

def add(a, b, /):
return a + b
print(add(3, 4))

جواب: 7


---

86. تابع که خودش را از طریق globals صدا می‌زند

def call_self(n):
if n > 0:
print(n)
globals()['call_self'](n-1)
call_self(3)

جواب:

3
2
1


---

87. تابع با decorator که ورودی و خروجی را چاپ می‌کند

def log(func):
def wrapper(*args, **kwargs):
print("Args:", args)
result = func(*args, **kwargs)
print("Result:", result)
return result
return wrapper
@log
def add(a, b):
return a + b
add(2, 5)

جواب:

Args: (2, 5)
Result: 7


---

88. تابع با multiple decorators

def deco1(func):
def wrapper():
print("deco1 start")
func()
print("deco1 end")
return wrapper

def deco2(func):
def wrapper():
print("deco2 start")
func()
print("deco2 end")
return wrapper

@deco1
@deco2
def say_hi():
print("Hi")

say_hi()

جواب:

deco1 start
deco2 start
Hi
deco2 end
deco1 end


---

89. تابع که تابع دیگر را به عنوان پارامتر می‌گیرد

def execute(func):
func()
execute(lambda: print("Hello"))

جواب: Hello


---

90. تابع که چندین مقدار را با return برمی‌گرداند و unpack می‌کند

def calc(a, b):
return a+b, a*b
s, m = calc(3, 4)
print(s, m)

جواب:
7 12


---

91. تابع که با recursion عدد را به باینری تبدیل می‌کند

def to_binary(n):
if n == 0:
return ""
return to_binary(n // 2) + str(n % 2)
print(to_binary(5))

جواب: 101


---

92. تابع generator بی‌نهایت

def infinite_numbers():
n = 0
while True:
yield n
n += 1
gen = infinite_numbers()
print(next(gen))
print(next(gen))

جواب:

0
1


---

93. تابع که list comprehension را برمی‌گرداند

def squares(n):
return [x**2 for x in range(n)]
print(squares(4))

جواب: [0, 1, 4, 9]


---

94. تابع که dict comprehension را برمی‌گرداند

def mapping(n):
return {x: x**2 for x in range(1, n+1)}
print(mapping(3))

جواب: {1: 1, 2: 4, 3: 9}


---

95. تابع که set comprehension را برمی‌گرداند

def unique_squares(lst):
return {x**2 for x in lst}
print(unique_squares([1,2,2,3]))

جواب: {1, 4, 9}


---

96. تابع با استفاده از any

def has_even(lst):
return any(x % 2 == 0 for x in lst)
print(has_even([1,3,5,8]))

جواب: True


---

97. تابع با استفاده از all

def all_positive(lst):
return all(x > 0 for x in lst)
print(all_positive([1,2,3]))

جواب: True


---

98. تابع که با recursion طول لیست را پیدا می‌کند

def length(lst):
if not lst:
return 0
return 1 + length(lst[1:])
print(length([1,2,3]))

جواب: 3


---

99. تابع که خودش را n بار صدا می‌زند

def repeat(func, n):
if n <= 0:
return
func()
repeat(func, n-1)
repeat(lambda: print("Hi"), 3)

جواب:

Hi
Hi
Hi


---

100. تابع که exception را درون خودش مدیریت می‌کند

def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
print(divide(10, 2))
print(divide(5, 0))

جواب:

5.0
Cannot divide by zero
فصل مدیریت فایل‌ها


---

فصل مدیریت فایل‌ها – ۱۰۰ سؤال


---

بخش ۱: ساده (سوال 1–20)

1. باز کردن و خواندن کل فایل

f = open("test.txt", "r")
print(f.read())
f.close()


---

2. خواندن بخشی از فایل

f = open("test.txt", "r")
print(f.read(5))
f.close()


---

3. خواندن یک خط

f = open("test.txt", "r")
print(f.readline())
f.close()


---

4. خواندن همه خطوط به صورت لیست

f = open("test.txt", "r")
print(f.readlines())
f.close()


---

5. حلقه روی خطوط فایل

f = open("test.txt", "r")
for line in f:
print(line.strip())
f.close()


---

6. نوشتن در فایل (حالت w)

f = open("new.txt", "w")
f.write("Hello World")
f.close()


---

7. اضافه کردن به فایل (حالت a)

f = open("new.txt", "a")
f.write("\nNew line")
f.close()


---

8. ایجاد فایل خالی (حالت x)

f = open("empty.txt", "x")
f.close()


---

9. استفاده از with برای خواندن

with open("test.txt", "r") as f:
print(f.read())


---

10. استفاده از with برای نوشتن

with open("new.txt", "w") as f:
f.write("Hi there")


---

11. بررسی وجود فایل با try

try:
f = open("test.txt", "r")
print(f.read())
f.close()
except FileNotFoundError:
print("File not found")


---

12. خواندن فایل باینری

with open("image.png", "rb") as f:
data = f.read()
print(type(data))


---

13. نوشتن فایل باینری

data = b"hello"
with open("data.bin", "wb") as f:
f.write(data)


---

14. تعیین encoding

with open("utf.txt", "w", encoding="utf-8") as f:
f.write("سلام")


---

15. خواندن فایل با encoding

with open("utf.txt", "r", encoding="utf-8") as f:
print(f.read())


---

16. پاک کردن محتوای فایل

open("test.txt", "w").close()


---

17. شمارش تعداد خطوط

with open("test.txt", "r") as f:
print(len(f.readlines()))


---

18. خواندن بدون خط جدید

with open("test.txt", "r") as f:
print(f.read().strip())


---

19. چک کردن writable بودن

with open("test.txt", "w") as f:
print(f.writable())


---

20. چک کردن readable بودن

with open("test.txt", "r") as f:
print(f.readable())


---
21. خواندن خط به خط با enumerate

with open("test.txt", "r") as f:
for i, line in enumerate(f, start=1):
print(i, line.strip())


---

22. نوشتن چند خط با writelines

lines = ["Line1\n", "Line2\n"]
with open("multi.txt", "w") as f:
f.writelines(lines)


---

23. خواندن و strip کردن هر خط

with open("test.txt", "r") as f:
print([line.strip() for line in f])


---

24. بررسی وجود فایل با os.path

import os
print(os.path.exists("test.txt"))


---

25. گرفتن سایز فایل

import os
print(os.path.getsize("test.txt"))


---

26. گرفتن مسیر کامل فایل

import os
print(os.path.abspath("test.txt"))


---

27. حذف فایل

import os
os.remove("test.txt")


---

28. تغییر نام فایل

import os
os.rename("old.txt", "new.txt")


---

29. کپی فایل

import shutil
shutil.copy("a.txt", "b.txt")


---

30. جابجایی فایل

import shutil
shutil.move("b.txt", "folder/b.txt")


---

31. خواندن فقط ۱۰ کاراکتر اول

with open("test.txt", "r") as f:
print(f.read(10))


---

32. رفتن به موقعیت خاص در فایل

with open("test.txt", "r") as f:
f.seek(5)
print(f.read())


---

33. گرفتن موقعیت فعلی

with open("test.txt", "r") as f:
f.read(4)
print(f.tell())


---

34. باز کردن فایل فقط خواندنی

f = open("test.txt", "rt")
print(f.mode)
f.close()


---

35. باز کردن فایل فقط نوشتنی

f = open("write.txt", "wt")
print(f.mode)
f.close()


---

36. باز کردن فایل فقط append

f = open("append.txt", "at")
print(f.mode)
f.close()


---

37. بستن خودکار با with

with open("test.txt") as f:
print(f.closed)
print(f.closed)


---

38. خواندن فایل خط‌به‌خط و حذف خط خالی

with open("test.txt", "r") as f:
for line in f:
if line.strip():
print(line.strip())


---

39. نوشتن شماره خط قبل از محتوا

with open("test.txt", "r") as f:
lines = f.readlines()
with open("out.txt", "w") as f:
for i, line in enumerate(lines, 1):
f.write(f"{i}: {line}")


---

40. الحاق محتوا از یک فایل به فایل دیگر

with open("a.txt", "r") as f1, open("b.txt", "a") as f2:
f2.write(f1.read())


---

بخش ۳: پیشرفته (سوال 41–60)

41. کار با JSON – ذخیره

import json
data = {"name": "Ali", "age": 25}
with open("data.json", "w") as f:
json.dump(data, f)


---

42. کار با JSON – خواندن

import json
with open("data.json", "r") as f:
obj = json.load(f)
print(obj)


---

43. کار با CSV – نوشتن

import csv
rows = [["Name", "Age"], ["Ali", 25]]
with open("people.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)


---

44. کار با CSV – خواندن

import csv
with open("people.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)


---

45. کار با Pickle – ذخیره

import pickle
data = [1, 2, 3]
with open("data.pkl", "wb") as f:
pickle.dump(data, f)


---

46. کار با Pickle – خواندن

import pickle
with open("data.pkl", "rb") as f:
obj = pickle.load(f)
print(obj)


---

47. شمارش تعداد کاراکترها در فایل

with open("test.txt", "r") as f:
print(len(f.read()))


---

48. شمارش تعداد کلمات

with open("test.txt", "r") as f:
print(len(f.read().split()))


---

49. شمارش تعداد خطوط غیرخالی

with open("test.txt", "r") as f:
print(sum(1 for line in f if line.strip()))


---

50. جستجو یک کلمه در فایل

word = "Ali"
with open("test.txt", "r") as f:
print(any(word in line for line in f))


---

51. جایگزینی متن در فایل

with open("test.txt", "r") as f:
data = f.read().replace("old", "new")
with open("test.txt", "w") as f:
f.write(data)


---

52. معکوس کردن خطوط فایل

with open("test.txt", "r") as f:
lines = f.readlines()
with open("test.txt", "w") as f:
f.writelines(lines[::-1])


---

53. نوشتن شماره خط و تعداد کاراکتر

with open("test.txt", "r") as f:
for i, line in enumerate(f, 1):
print(i, len(line.strip()))


---

54. پیدا کردن طولانی‌ترین خط

with open("test.txt", "r") as f:
print(max(f, key=len))


---

55. حذف خطوط تکراری

with open("test.txt", "r") as f:
lines = list(dict.fromkeys(f))
with open("test.txt", "w") as f:
f.writelines(lines)


---

56. ادغام چند فایل متنی
files = ["a.txt", "b.txt"]
with open("merged.txt", "w") as out:
for file in files:
with open(file, "r") as f:
out.write(f.read() + "\n")


---

57. کپی باینری با read/write

with open("img.png", "rb") as f1, open("copy.png", "wb") as f2:
f2.write(f1.read())


---

58. نوشتن لیست در فایل با join

lst = ["a", "b", "c"]
with open("letters.txt", "w") as f:
f.write("\n".join(lst))


---

59. خواندن و تبدیل به لیست اعداد

with open("nums.txt", "r") as f:
nums = [int(x) for x in f.read().split()]
print(nums)


---

60. ساخت فایل log

with open("log.txt", "a") as f:
f.write("Event happened\n")
61. استفاده از pathlib برای خواندن فایل

from pathlib import Path
print(Path("test.txt").read_text())


---

62. استفاده از pathlib برای نوشتن فایل

from pathlib import Path
Path("hello.txt").write_text("Hello World")


---

63. بررسی وجود فایل با pathlib

from pathlib import Path
print(Path("test.txt").exists())


---

64. گرفتن پسوند فایل

from pathlib import Path
print(Path("data.csv").suffix)


---

65. گرفتن نام فایل بدون پسوند

from pathlib import Path
print(Path("data.csv").stem)


---

66. لیست‌کردن همه فایل‌های پوشه

from pathlib import Path
for file in Path(".").iterdir():
print(file)


---

67. پیدا کردن همه فایل‌های txt در پوشه

from pathlib import Path
for file in Path(".").glob("*.txt"):
print(file)


---

68. پیدا کردن فایل‌های txt در همه زیرپوشه‌ها

from pathlib import Path
for file in Path(".").rglob("*.txt"):
print(file)


---

69. تغییر نام فایل با pathlib

from pathlib import Path
Path("old.txt").rename("new.txt")


---

70. حذف فایل با pathlib

from pathlib import Path
Path("delete.txt").unlink()


---

71. خواندن فایل خط‌به‌خط با pathlib

from pathlib import Path
for line in Path("test.txt").read_text().splitlines():
print(line)


---

72. ترکیب مسیرها با / در pathlib

from pathlib import Path
p = Path("folder") / "file.txt"
print(p)


---

73. بررسی اینکه مسیر فایل است یا پوشه

from pathlib import Path
print(Path("test.txt").is_file())
print(Path(".").is_dir())


---

74. گرفتن اندازه فایل با pathlib

from pathlib import Path
print(Path("test.txt").stat().st_size)


---

75. گرفتن تاریخ آخرین تغییر

from pathlib import Path
import datetime
time = Path("test.txt").stat().st_mtime
print(datetime.datetime.fromtimestamp(time))


---

76. خواندن و حذف فاصله‌ها از هر خط

with open("test.txt") as f:
print([line.strip() for line in f])


---

77. کپی فایل با pathlib + shutil

from pathlib import Path
import shutil
shutil.copy(Path("a.txt"), Path("b.txt"))


---

78. ذخیره‌سازی دیکشنری به JSON با indent

import json
data = {"a": 1, "b": 2}
with open("data.json", "w") as f:
json.dump(data, f, indent=4)


---

79. خواندن فایل CSV به لیست دیکشنری‌ها

import csv
with open("people.csv", "r") as f:
reader = csv.DictReader(f)
print(list(reader))


---

80. نوشتن لیست دیکشنری‌ها در CSV

import csv
rows = [{"Name": "Ali", "Age": 25}, {"Name": "Sara", "Age": 30}]
with open("people.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["Name", "Age"])
writer.writeheader()
writer.writerows(rows)


---

بخش ۵: ترکیبی و حرفه‌ای (سوال 81–100)

81. خواندن لاگ و فیلتر خط‌های دارای ERROR

with open("log.txt") as f:
for line in f:
if "ERROR" in line:
print(line.strip())


---

82. شمارش تعداد تکرار یک کلمه در فایل

word = "Python"
with open("test.txt") as f:
print(f.read().count(word))


---

83. ادغام همه فایل‌های txt در یک فایل

from pathlib import Path
with open("merged.txt", "w") as out:
for file in Path(".").glob("*.txt"):
out.write(file.read_text() + "\n")


---

84. ایجاد فایل بکاپ قبل از ویرایش

import shutil
shutil.copy("data.txt", "data_backup.txt")


---

85. خواندن بزرگ‌ترین فایل در یک پوشه

from pathlib import Path
print(max(Path(".").iterdir(), key=lambda p: p.stat().st_size))


---

86. حذف همه فایل‌های خالی

from pathlib import Path
for file in Path(".").glob("*"):
if file.is_file() and file.stat().st_size == 0:
file.unlink()


---

87. ذخیره متن ورودی کاربر در فایل

text = input("Enter text: ")
with open("user.txt", "w") as f:
f.write(text)


---

88. خواندن اولین n خط فایل

n = 3
with open("test.txt") as f:
for i in range(n):
print(f.readline().strip())


---

89. خواندن آخرین n خط فایل

n = 2
with open("test.txt") as f:
lines = f.readlines()
print(lines[-n:])


---

90. چک کردن دسترسی خواندن/نوشتن فایل

import os
print(os.access("test.txt", os.R_OK))
print(os.access("test.txt", os.W_OK))


---

91. نوشتن داده باینری از ورودی کاربر

data = b"12345"
with open("bin.bin", "wb") as f:
f.write(data)


---

92. خواندن فایل JSON و چاپ مقدار خاص
import json
with open("data.json") as f:
data = json.load(f)
print(data["name"])


---

93. جستجو رشته در چند فایل

from pathlib import Path
for file in Path(".").glob("*.txt"):
if "Python" in file.read_text():
print(file)


---

94. پیدا کردن طولانی‌ترین کلمه در فایل

with open("test.txt") as f:
words = f.read().split()
print(max(words, key=len))


---

95. ذخیره داده با فرمت YAML

import yaml
data = {"name": "Ali", "age": 25}
with open("data.yaml", "w") as f:
yaml.dump(data, f)


---

96. خواندن داده از YAML

import yaml
with open("data.yaml") as f:
print(yaml.safe_load(f))


---

97. تبدیل JSON به CSV

import json, csv
with open("data.json") as f:
data = json.load(f)
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(data.keys())
writer.writerow(data.values())


---

98. خواندن CSV و ذخیره در JSON

import csv, json
with open("people.csv") as f:
reader = csv.DictReader(f)
data = list(reader)
with open("people.json", "w") as f:
json.dump(data, f)


---

99. خواندن و مرتب‌سازی خطوط فایل

with open("test.txt") as f:
lines = sorted(f.readlines())
with open("sorted.txt", "w") as f:
f.writelines(lines)


---

100. مدیریت خطا هنگام باز کردن فایل

try:
with open("nofile.txt") as f:
print(f.read())
except FileNotFoundError:
print("File not found!")
فصل خطاها و استثناها (Exceptions)

ساختار فصل





---

بخش ۱ – ساده (سوال ۱ تا ۲۰)

1. گرفتن خطای تقسیم بر صفر

try:
x = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero")

2. گرفتن خطای مقدار نامعتبر در int

try:
x = int("abc")
except ValueError:
print("Invalid integer")

3. گرفتن خطای باز کردن فایل غیر موجود

try:
f = open("nofile.txt")
except FileNotFoundError:
print("File not found")

4. گرفتن چند نوع خطا در یک except

try:
num = int("abc")
except (ValueError, TypeError):
print("Error in conversion")

5. استفاده از متغیر خطا

try:
1 / 0
except ZeroDivisionError as e:
print("Error:", e)

6. استفاده از else در try-except

try:
x = int("10")
except ValueError:
print("Error")
else:
print("Success:", x)

7. استفاده از finally برای بستن فایل

try:
f = open("data.txt", "w")
f.write("Hello")
finally:
f.close()
print("File closed")

8. گرفتن خطای IndexError

try:
nums = [1, 2]
print(nums[5])
except IndexError:
print("Index out of range")

9. گرفتن خطای KeyError

try:
d = {"a": 1}
print(d["b"])
except KeyError:
print("Key not found")

10. گرفتن خطای TypeError

try:
print(5 + "hi")
except TypeError:
print("Type mismatch")

11. گرفتن خطای NameError

try:
print(x)
except NameError:
print("Variable not defined")

12. جلوگیری از قطع برنامه با try-except

try:
1 / 0
except ZeroDivisionError:
print("Handled error, program continues")
print("End")

13. تست چندین except جداگانه

try:
int("abc")
except ValueError:
print("Value error")
except TypeError:
print("Type error")

14. گرفتن خطای AttributeError

try:
None.append(1)
except AttributeError:
print("No such attribute")

15. گرفتن خطای ImportError

try:
import non_existing_module
except ImportError:
print("Module not found")

16. گرفتن خطای OverflowError

try:
import math
math.exp(1000)
except OverflowError:
print("Number too large")

17. گرفتن خطای MemoryError

try:
x = [1] * (10**10)
except MemoryError:
print("Out of memory")

18. گرفتن خطای IOError

try:
f = open("/root/test.txt", "r")
except IOError:
print("Cannot open file")

19. گرفتن خطای UnicodeDecodeError

try:
with open("file.txt", encoding="ascii") as f:
print(f.read())
except UnicodeDecodeError:
print("Encoding error")

20. گرفتن خطای RuntimeError

try:
raise RuntimeError("Custom runtime error")
except RuntimeError as e:
print("Caught:", e)

21. استفاده از pass برای نادیده گرفتن خطا

try:
1 / 0
except ZeroDivisionError:
pass
print("Program continues")

22. چاپ نوع خطا با type()

try:
int("abc")
except Exception as e:
print(type(e))

23. گرفتن همه خطاها با Exception

try:
x = undefined_var
except Exception:
print("Some error occurred")

24. گرفتن خطا و پیامش با str(e)

try:
int("abc")
except Exception as e:
print("Error:", str(e))

25. استفاده از چندین except و else

try:
num = int("10")
except ValueError:
print("Invalid")
else:
print("OK:", num)

26. استفاده از چندین except و finally

try:
5 / 0
except ValueError:
print("Value error")
except ZeroDivisionError:
print("Divide by zero")
finally:
print("Done")

27. گرفتن خطای توقف حلقه با KeyboardInterrupt

try:
while True:
pass
except KeyboardInterrupt:
print("Stopped by user")

28. مدیریت خطا در تابع

def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return None
print(divide(5, 0))

29. بازگرداندن مقدار پیش‌فرض در خطا

def to_int(s):
try:
return int(s)
except ValueError:
return 0
print(to_int("abc"))

30. استفاده از assert و گرفتن AssertionError

try:
assert 2 + 2 == 5
except AssertionError:
print("Assertion failed")

31. گرفتن خطای بازگشتی بیش از حد (RecursionError)

def f():
f()
try:
f()
except RecursionError:
print("Max recursion depth reached")

32. گرفتن خطای StopIteration

it = iter([1])
try:
next(it)
next(it)
except StopIteration:
print("No more items")

33. استفاده از try در لیست‌کامپری‌هنشن
data = ["1", "x", "2"]
nums = [int(x) if x.isdigit() else 0 for x in data]
print(nums)

34. گرفتن خطای ValueError هنگام تبدیل لیست

data = ["10", "abc", "20"]
for x in data:
try:
print(int(x))
except ValueError:
print("Invalid:", x)

35. گرفتن خطای AttributeError در کلاس

class Test:
pass
try:
Test().hello()
except AttributeError:
print("No such method")

36. گرفتن خطای FileExistsError

import os
try:
os.mkdir("folder")
os.mkdir("folder")
except FileExistsError:
print("Folder exists")

37. گرفتن خطای PermissionError

try:
with open("/root/test.txt", "w") as f:
f.write("Hi")
except PermissionError:
print("Permission denied")

38. گرفتن خطای ModuleNotFoundError

try:
import not_a_module
except ModuleNotFoundError:
print("Module not found")

39. گرفتن خطای LookupError (پایه برای IndexError/KeyError)

try:
{}["x"]
except LookupError:
print("Lookup error")

40. گرفتن خطای ArithmeticError (پایه برای ZeroDivisionError)

try:
1 / 0
except ArithmeticError:
print("Arithmetic error")

41. استفاده از raise برای ایجاد خطا

x = -5 if x < 0: raise ValueError("x must be positive")

42. ایجاد خطای سفارشی با کلاس جدید

class MyError(Exception): pass raise MyError("Custom error occurred")

43. ایجاد خطای سفارشی و گرفتن آن

class MyError(Exception): pass try: raise MyError("Something wrong") except MyError as e: print(e)

44. استفاده از raise در تابع

def check_age(age): if age < 18: raise ValueError("Underage") check_age(15)

45. پرتاب خطا داخل except دیگر

try: int("abc") except ValueError: raise TypeError("Wrong type")

46. استفاده از from برای زنجیره خطاها

try: int("abc") except ValueError as e: raise RuntimeError("Failed") from e

47. خطای assert و پیام سفارشی

assert 2 + 2 == 4, "Math is broken!"

48. استفاده از finally حتی با raise

try: raise ValueError finally: print("Always runs")

49. گرفتن چند خطا با یک except tuple

try: x = int("abc") except (ValueError, TypeError): print("Value or type error")

50. بازنشر خطا با raise بدون آرگومان

try: 1 / 0 except ZeroDivisionError: print("Logging...") raise

51. استفاده از warnings برای هشدار

import warnings warnings.warn("This is a warning", UserWarning)

52. تبدیل هشدار به استثنا

import warnings warnings.simplefilter("error") warnings.warn("Will become error", UserWarning)

53. گرفتن TypeError

try: "a" + 1 except TypeError: print("Type error")

54. گرفتن خطای ImportError

try: from math import unknown_func except ImportError: print("Import error")

55. استفاده از try/except تو در تو

try: try: 1 / 0 except ZeroDivisionError: print("Inner error") except Exception: print("Outer error")

56. استفاده از متغیر خطا خارج از except

try: 1 / 0 except ZeroDivisionError as e: err = e print(err)

57. استفاده از sys.exc_info()

import sys try: 1 / 0 except: print(sys.exc_info())

58. مدیریت خطا در لیست‌پردازی

data = ["1", "x", "2"] nums = [] for s in data: try: nums.append(int(s)) except ValueError: nums.append(0) print(nums)

59. استفاده از contextlib.suppress()

from contextlib import suppress with suppress(FileNotFoundError): open("nofile.txt")

60. بستن منابع حتی با خطا

try: f = open("test.txt") 1 / 0 finally: f.close()

بخش ۴ – ترکیبی و حرفه‌ای (سوال ۶۱ تا ۸۰)

61. مدیریت چند عملیات حساس با یک try

try: a = int("10") b = a / 0 except (ValueError, ZeroDivisionError) as e: print("Error:", e)

62. ایجاد خطای سفارشی با پارامترهای بیشتر

class InputError(Exception): def init(self, value, message): self.value = value self.message = message super().init(message) raise InputError(10, "Invalid input")

63. استفاده از raise در شرط

x = None if x is None: raise RuntimeError("x is required")

64. مدیریت خطا در باز کردن فایل

try: with open("nofile.txt") as f: print(f.read()) except FileNotFoundError: print("File not found")

65. ایجاد خطای منطقی خودکار

def divide(a, b): if b == 0: raise ZeroDivisionError return a / b

66. استفاده از assert برای ورودی‌ها

def factorial(n): assert n >= 0, "n must be non-negative" return 1 if n == 0 else n * factorial(n - 1)

67. زنجیره خطاهای سفارشی
class ErrorA(Exception): pass class ErrorB(Exception): pass try: raise ErrorA except ErrorA as e: raise ErrorB from e

68. تبدیل همه خطاها به RuntimeError

try: int("abc") except Exception as e: raise RuntimeError from e

69. خطا در comprehension با try داخلی

data = ["1", "x"] nums = [int(x) if x.isdigit() else 0 for x in data]

70. استفاده از logging برای ثبت خطا

import logging try: 1 / 0 except ZeroDivisionError: logging.exception("Error occurred")

71. جلوگیری از خطا با isinstance

x = "5" if isinstance(x, int): print(x + 1) else: print("Not int")

72. گرفتن MemoryError

try: x = "a" * (10**10) except MemoryError: print("Out of memory")

73. استفاده از atexit برای تمیزکاری

import atexit atexit.register(lambda: print("Cleaning up")) raise RuntimeError

74. گرفتن خطای OSError

import os try: os.remove("nofile.txt") except OSError as e: print("OS error:", e)

75. گرفتن خطای RuntimeError

try: raise RuntimeError("Something bad happened") except RuntimeError as e: print(e)

76. گرفتن خطای ValueError در map

data = ["1", "x", "2"] try: list(map(int, data)) except ValueError as e: print(e)

77. مدیریت خطا در yield generator

def gen(): try: yield 1 / 0 except ZeroDivisionError: yield 0 print(list(gen()))

78. بازگرداندن پیام خطا به کاربر

def safe_div(a, b): try: return a / b except ZeroDivisionError as e: return str(e) print(safe_div(1, 0))

79. استفاده از exit هنگام خطا

import sys try: raise ValueError except ValueError: sys.exit("Fatal error")

80. مدیریت خطای JSON

import json try: json.loads("{bad json}") except json.JSONDecodeError: print("Invalid JSON")

بخش ۵ – فوق‌پیشرفته و ترکیبی (سوال ۸۱ تا ۱۰۰)

81. گرفتن خطا در چند سطح تابع

def a(): b() def b(): c() def c(): 1 / 0 try: a() except ZeroDivisionError: print("Caught")

82. گرفتن خطای UnicodeDecodeError

try: open("file.txt", encoding="ascii").read() except UnicodeDecodeError: print("Encoding error")

83. خطای UnicodeEncodeError

try: "سلام".encode("ascii") except UnicodeEncodeError: print("Cannot encode")

84. گرفتن خطای IndexError و پیام

try: [1, 2][5] except IndexError as e: print(e)

85. گرفتن خطای KeyError با مقدار پیش‌فرض

d = {"a": 1} try: print(d["b"]) except KeyError: print("Default value")

86. مدیریت چند خطا در حلقه بزرگ

items = [1, 0, "x"] for i in items: try: print(10 / i) except (TypeError, ZeroDivisionError) as e: print("Error:", e)

87. خطا در بازکردن URL

import urllib.request try: urllib.request.urlopen("http://invalid.url") except Exception as e: print("URL error:", e)

88. بازنشر خطا بعد از لاگ کردن

try: 1 / 0 except ZeroDivisionError as e: print("Logging:", e) raise

89. گرفتن خطا در threading

import threading def task(): raise ValueError t = threading.Thread(target=task) t.start() t.join() print("Thread done (error not caught here)")

90. گرفتن خطا در multiprocessing

from multiprocessing import Process def task(): raise ValueError p = Process(target=task) p.start() p.join() print("Process ended")

91. استفاده از try در context manager

class MyCM: def enter(self): return self def exit(self, exc_type, exc, tb): print("Error type:", exc_type) with MyCM(): 1 / 0

92. جلوگیری از توقف برنامه با except گسترده

while True: try: 1 / int(input("Number: ")) except: print("Error")

93. ذخیره جزئیات خطا در فایل

import traceback try: 1 / 0 except: with open("error.log", "w") as f: traceback.print_exc(file=f)

94. استفاده از traceback.format_exc()

import traceback try: 1 / 0 except: print(traceback.format_exc())

95. خطای EOFError در ورودی

try: input() except EOFError: print("No input")

96. خطای OverflowError

try: import math math.exp(1000) except OverflowError: print("Too large")

97. گرفتن خطای NotImplementedError

def f(): raise NotImplementedError try: f() except NotImplementedError: print("Not implemented")

98. گرفتن خطای ZeroDivisionError در float

try: 1.0 / 0.0 except ZeroDivisionError: print("Float division by zero")

99. گرفتن خطای socket

import socket try: socket.socket().connect(("invalid", 80)) except Exception as e: print("Socket error:", e)

100. گرفتن تمام خطاها و ادامه کار
for x in [1, 0, "x"]: try: print(10 / x) except Exception as e: print("Error:", e)
فصل کلاس‌ها و شیءگرایی (OOP)

بخش ۱ – مفاهیم پایه کلاس (سوال ۱ تا ۲۰)
1. تعریف یک کلاس ساده
class Person: pass
2. ایجاد شی از کلاس
class Person: pass p = Person()
3. افزودن ویژگی به شی بعد از ایجاد
class Person: pass p = Person() p.name = "Ali"
4. متد سازنده init
class Person: def __init__(self, name): self.name = name
5. ایجاد دو شی با مقادیر متفاوت
p1 = Person("Ali") p2 = Person("Sara")
6. افزودن متد به کلاس
class Person: def say_hello(self): print("Hello!")
7. متد با استفاده از ویژگی داخلی
class Person: def __init__(self, name): self.name = name def greet(self): print(f"Hello {self.name}")
8. تغییر ویژگی بعد از ساخت شی
p = Person("Ali") p.name = "Reza"
9. حذف ویژگی با del
del p.name
10. متد با پارامتر ورودی
class Calculator: def add(self, x, y): return x + y
11. استفاده از self برای دسترسی به ویژگی‌ها
class Counter: def __init__(self): self.count = 0 def inc(self): self.count += 1
12. ایجاد ویژگی پیش‌فرض
class Person: def __init__(self, name="Unknown"): self.name = name
13. نماstrار شی با __str__
class Person: def __init__(self, name): self.name = name def __str__(self): return f"Person({self.name})"
14. استفاده از __repr__ برای نreprی
class Person: def __repr__(self): return "Person object"
15. مقایسه اinit_eq__
class Person: def __init__(self, name): self.name = name def __eq__(self, other): return self.name == other.name
16. شمارش تعداد اشیای ساinitclass Person: count = 0 def __init__(self): Person.count += 1
17. ویژگی کلاس در مقابل ویژگی شی
class A: x = 10 a1 = A() a2 = A() a1.x = 20
18. پاک کردن ویژگی کلاس
del A.x
19. استفاده از docstring در کلاس
class Person: """This class represents a person."""
20. بررسی نوع شی با isinstance
isinstance(p, Person)
21. متد کلاس (@classmethod)
class MyClass: count = 0 @classmethod def inc(cls): cls.count += 1
22. استفاده از متد کلاس برای ساخت شی
class Person: def __init__(self, name): self.name = name @classmethod def from_list(cls, names): return [cls(name) for name in names]
23. متد استاتیک (@staticmethod)
class Math: @staticmethod def add(a, b): return a + b
24. تفاوت متد استاتیک و کلاس
Math.add(2, 3) # بدون نیاز به self یا cls
25. ویژگی خصوصی با دو خط زیر
class Person: def __init__(self, name): self.__name = name
26. متد خصوصی با دو خط زیر
class Person: def __secret(self): print("Hidden")
27. دسترسی به ویژگی خصوصی با name mangling
p._Person__name
28. ویژگی فقط خواندنی با property
class Person: def __init__(self, age): self._age = age @property def age(self): return self._age
29. ویژگی خواندنی/نوشتنی با setter
class Person: @property def name(self): return self._name @name.setter def name(self, value): self._name = value
30. حذف ویژگی با deleter
class Person: @property def name(self): return self._name @name.deleter def name(self): del self._name
31. شمارش اشیا با متد کلاس
class Person: count = 0 def __init__(self): Person.count += 1 @classmethod def total(cls): return cls.count
32. اضافه کردن ویژگی به صورت داینامیک
p = Person() setattr(p, "age", 25)
33. گرفتن مقدار ویژگی به صورت داینامیک
getattr(p, "age")
34. بررسی وجود ویژگی
hasattr(p, "age")
35. حذف ویژگی داینامیک
delattr(p, "age")
36.dirه از متد __dir__
dir(p)
37. ذخیره‌سازی همه اشیا در یک لیست
class Person: all_objects = [] def __init__(self): Person.all_objects.append(self)
38. شمdictویژdict __dict__
p.__dict__
39. تغییر ویژگی کلاس در تمام اشیا
Person.count = 100
40. تعریف متدهای متعدد برای یک کلاس
class Person: def greet(self): pass def walk(self): pass
بخش ۳ – وراثت و چندریختی (سوال 41 تا 60)
41. تعریف کلاس فرزند
class Animal: pass class Dog(Animal): pass
42. وراثت سازنده والد
class Animal: def __init__(self, name): self.name = name class Dog(Animal): def __init__(self, name, breed): super().__init__(name) self.breed = breed
43. متد override در کلاس فرزند
class Dog(Animal): def speak(self): print("Woof!")
44. استفاده از super() برای فراخوانی متد والد
class Dog(Animal): def speak(self): super().speak() print("Woof!")
45. چندریختی با متد مشترک
for animal in [Dog(), Cat()]: animal.speak()
46. چند وراثتی
class A: pass class B: pass class C(A, B): pass
47. ترتیب جستجوی متدها (MRO)
C.mro()
48. متد کلاس والد در چند وراثتی
super(A, self).method()
49. کلاس انتزاعی با abc
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass
50. پیاده‌سازی کلاس انتزاعی
class Circle(Shape): def area(self): return 3.14 * r * r
51. استفاده از متدهای انتزاعی در چندریختی
shapes = [Circle(), Square()] for s in shapes: print(s.area())
52. جلوگیری از وراثت باinit
class Final(type): def __init__(cls, name, bases, attrs): for base in bases: if isinstance(base, Final): raise TypeError("Can't inherit")
53. ارث‌برbasesای کلاس والد
print(Dog.__bases__)
54. اضافه کردن ویژگی به والد و دیدن در فرزند
Animal.legs = 4
55. تغییر ویژگی کلاس والد از فرزند
Dog.legs = 3
56. استفاده از isinstance برای بررسی نوع فرزند
isinstance(Dog(), Animal)
57. استفاده از issubclass برای بررسی وراثت
issubclass(Dog, Animal)
58. چندریختی با __str__
print([str(obj) for obj in [Dog(), Cat()]])
59. سازنده خالی در کلاس فرزند
class Dog(Animal): pass
60. متد والد بدون تغییر در فرزند
Dog().parent_method()
بخش ۴ – ویژگی‌های پیشرفته (سوال 61 add61. استفاده از متدهinitی __add__
class Vector: def __init__(self, x): self.x = x def __add__(self, other): return Vector(self.x + other.x)
62. متد جادویی __len__
def __len__(self): return len(self.items)
63. متد جادویی __getitem__
def __getitem__(self, index): return self.data[index]
64. متد جادویی __setitem__
def __setitem__(self, index, value): self.data[index] = value
65. متد جادiterer__
def __iter__(self): return iter(self.data)
66. متدcall__call__
def __call__(self): print("Object called")
67.enterیی exit_ و __exit__ برای context manager
class MyFile: def __enter__(self): pass def __exit__(self, exc_type, exc, tb): pass
68. استفاده از context manager در کلاس
with MyFile() as f: pass
69. متد جادویی __delرای تخریب شی
def __del__(self): print("Deleted")
70. ذخیره و بارگذاری شی با pickle
import pickle pickle.dump(obj, open("obj.pkl", "wb"))
71. بارگذاری شی pickle شده
obj = pickle.load(open("obj.pkl", "rb"))
72. استفاده از اسلات‌ها برای صرفه‌جslots
class Person: __slots__ = ['name', 'age']
73. contains_contains__
def __contains__(self, item): return item in self.data
74. متد جادویی __bool__
def __bool__(self): return bool(self.value)
75. متد جادویی __hash__
def __hash__(self): return hash(self.name)
76. متد جادویی __lt__ برای مرتب‌سازی
def __lt__(self, other): return self.value < other.value
77. initاز کلاس به عنوان دکوراتور
class MyDeco: def __init__(self, func): self.func = func def __call__(self, *a, **kw): return self.func(*a, **kw)
78. کلاس با متدهای classmethod و staticmethod ترکیبی
class Utility: @classmethod def cls_method(cls): pass @staticmethod def static_method(): pass
79. استفاده از کلاس به عنوان context manager پیشرفته
with Utility() as u: pass
80. اجرای خودکار متد در سازنده
class AutoRun: def __init__(self): self.run()
بخش ۵ – ترکیبی و کاربردی (سوال 81 تاinit. مدل‌سازی بانک با کلاس حساب
class BankAccount: def __init__(self, balance=0): self.balance = balance def deposit(self, amount): self.balance += amount
82. افزودن برداشت به کلاس حساب
def withdraw(self, amount): if amount <= self.balance: self.balance -= amount
83. کلاس مدیریت دانشجو
class Student: def __init__(self, name, grades=[]): self.name = name self.grades = grades
84. افزودن متد معدل‌گیری
def average(self): return sum(self.grades) / len(self.grades)
85. سیستم لاگین ساده
class User: def __init__(self, username, password): self.username = username self.password = password def check_password(self, pwd): return self.password == pwd
86. کلاس ماشین با متد رانندگی
class Car: def __init__(self, model): self.model = model def drive(self): print(f"{self.model} is driving")
87. کلاس کتابخانه با افزودن کتاب
class Library: def __init__(self): self.books = [] def add_book(self, book): self.books.append(book)
88. حذف کتاب از کتابخانه
def remove_book(self, book): self.books.remove(book)
89. سیستم سفارش آنلاین با کلاس Order
class Order: def __init__(self, items): self.items = items def total(self): return sum(price for _, price in self.items)
90. اضافه کردن تخفیف به سفارش
def apply_discount(self, percent): return self.total() * (1 - percent/100)
91. کلاس تایمر با time
import time class Timer: def start(self): self.start_time = time.time() def stop(self): print(time.time() - self.start_time)
92. کلاس add با عملگر +
class Counter: def __init__(self, value): self.value = value def __add__(self, other): return Counter(self.value + other.value)
93. کلاس Logger که به فایل می‌نویسد
class Logger: def log(self, msg): with open("log.txt", "a") as f: f.write(msg + "\n")
94. کلاس EmailSender
class EmailSender: def send(self, to, subject, body): print(f"Sending to {to}: {subject}")
95. کلاس با ویژگی محاسبه‌شونده
class Rectangle: def __init__(self, w, h): self.w, self.h = w, h @property def area(self): return self.w * self.h
96. کلاس ذخیره داده JSON
import json class DataStore: def save(self, data): json.dump(data, open("data.json", "w"))
97. کلاس بارگذاری داده JSON
def load(self): return json.load(open("data.json"))
98. کلاس مدیریت تنظیمات
class Config: settings = {} @classmethod def set(cls, key, value): cls.settings[key] = value
99. کلاس Singleton
class Singleton: _instance = None def __new__(cls): if not cls._instance: cls._instance = super().__new__(cls) return cls._instance
100. کلاس Factory برای ساخت اشیا
class Factory: @staticmethod def create(cls, *args, **kwargs): return cls(*args, **kwargs)
فصل ماژول‌ها و کتابخانه‌ها
1. ساخت یک ماژول ساده
# file: mymodule.py def greet(): print("Hello from module!")
2. ایمپورت ماژول
import mymodule mymodule.greet()
3. ایمپورت با نام مستعار
import mymodule as mm mm.greet()
4. ایمپورت فقط یک تابع
from mymodule import greet greet()
5. ایمپورت چند تابع
from mymodule import greet, another_func
6. استفاده از * برای ایمپورت همه
from mymodule import *
7. مکان پیش‌فرض جستجوی ماژول‌ها
import sys print(sys.path)
8. اضافه کردن مسیر جدید به sys.path
sys.path.append("/path/to/module")
9. استفاده از name برای شناسایی اجرای مستقیم
if __name__ == "__main__": greet()
10. بارگذاری دوباره ماژول
import importlib importlib.reload(mymodule)
11. تعریف متغیر در ماژول و استفاده در برنامه اصلی
# mymodule.py x = 10
12. تغییر متغیر ماژول از برنامه اصلی
mymodule.x = 20
13. ایجاد ماژول با کلاس
# mymodule.py class MyClass: pass
14. استفاده از کلاس ماژول
obj = mymodule.MyClass()
15. استفاده از تابع help برای ماژول
help(mymodule)
16. دیدن محل فایل ماژول
print(mymodule.__file__)
17. ساخت ماژول با کد اجرای مستقیم
# mymodule.py if __name__ == "__main__": print("Running module directly")
18. استفاده از dir() برای لیست توابع ماژول
dir(mymodule)
19. ماژول با داک‌استرینگ
"""My custom module for greeting users"""
20. استفاده از as برای تغییر نام ماژول وارد شده
import math as m print(m.sqrt(9))
بخش ۲ – کتابخانه‌های استاندارد پایتون (سوال 21 تا 50)
21. استفاده از math برای عملیات ریاضی
import math print(math.sqrt(16))
22. استفاده از random برای تولید عدد تصادفی
import random print(random.randint(1, 10))
23. انتخاب تصادفی از لیست
random.choice([1, 2, 3])
24. استفاده از datetime برای تاریخ و زمان
import datetime print(datetime.datetime.now())
25. تبدیل رشته به تاریخ
datetime.datetime.strptime("2025-08-14", "%Y-%m-%d")
26. کار با os برای دسترسی به فایل‌ها
import os print(os.listdir("."))
27. ساخت پوشه جدید با os
os.mkdir("new_folder")
28. حذف فایل با os
os.remove("file.txt")
29. استفاده از sys برای دریافت آرگومان‌ها
import sys print(sys.argv)
30. استفاده از json برای ذخیره‌سازی داده
import json json.dump({"name": "Ali"}, open("data.json", "w"))
31. بارگذاری داده JSON
data = json.load(open("data.json"))
32. استفاده از csv برای نوشتن فایل CSV
import csv with open("data.csv", "w") as f: writer = csv.writer(f) writer.writerow(["name", "age"])
33. خواندن فایل CSV
with open("data.csv") as f: reader = csv.reader(f) for row in reader: print(row)
34. استفاده از shutil برای کپی فایل
import shutil shutil.copy("data.csv", "backup.csv")
35. استفاده از glob برای یافتن فایل‌ها
import glob print(glob.glob("*.py"))
36. استفاده از pathlib برای مدیریت مسیرها
from pathlib import Path p = Path("test.txt") p.write_text("Hello")
37. استفاده از statistics برای محاسبه میانگین
import statistics statistics.mean([1, 2, 3])
38. فشرده‌سازی فایل با zipfile
import zipfile with zipfile.ZipFile("archive.zip", "w") as z: z.write("data.csv")
39. استخراج فایل zip
with zipfile.ZipFile("archive.zip", "r") as z: z.extractall("folder")
40. استفاده از time برای محاسبه زمان اجرا
import time start = time.time() time.sleep(1) print(time.time() - start)
41. استفاده از itertools برای تولید ترکیب‌ها
import itertools list(itertools.combinations([1,2,3], 2))
42. استفاده از functools برای دکوراتور cache
from functools import lru_cache @lru_cache() def slow(): pass
43. استفاده از operator برای عملیات سریع‌تر
import operator operator.add(2, 3)
44. استفاده از collections.Counter
from collections import Counter Counter("banana")
45. استفاده از namedtuple
from collections import namedtuple Point = namedtuple("Point", "x y") p = Point(1, 2)
46. استفاده از defaultdict
from collections import defaultdict d = defaultdict(int)
47. استفاده از re برای جستجوی الگو
import re re.findall(r"\d+", "abc123")
48. استفاده از hashlib برای هش کردن
import hashlib hashlib.sha256(b"test").hexdigest()
49. استفاده از tempfile برای ساخت فایل موقت
import tempfile with tempfile.NamedTemporaryFile() as tmp: print(tmp.name)
50. استفاده از uuid برای تولید شناسه یکتا
import uuid print(uuid.uuid4())
51. نصب کتابخانه با pip
pip install requests
52. بررسی نسخه کتابخانه نصب‌شده
pip show requests
53. به‌روزرسانی کتابخانه
pip install --upgrade requests
54. استفاده از requests برای گرفتن یک صفحه وب
import requests r = requests.get("https://example.com") print(r.text)
55. ارسال داده با POST در requests
requests.post("https://example.com", data={"key": "value"})
56. دانلود فایل با requests
r = requests.get("https://example.com/file.zip") open("file.zip", "wb").write(r.content)
57. استفاده از pandas برای خواندن CSV
import pandas as pd df = pd.read_csv("data.csv") print(df.head())
58. استفاده از pandas برای ذخیره CSV
df.to_csv("output.csv", index=False)
59. استفاده از numpy برای آرایه‌ها
import numpy as np arr = np.array([1,2,3])
60. استفاده از numpy برای عملیات برداری
arr * 2
61. استفاده از matplotlib برای ترسیم نمودار
import matplotlib.pyplot as plt plt.plot([1,2,3], [4,5,6]) plt.show()
62. استفاده از seaborn برای گراف پیشرفته
import seaborn as sns sns.histplot([1,2,3,4])
63. استفاده از openpyxl برای کار با اکسل
from openpyxl import Workbook wb = Workbook() ws = wb.active ws["A1"] = "Hello" wb.save("file.xlsx")
64. استفاده از Pillow برای کار با تصویر
from PIL import Image img = Image.open("pic.jpg") img.show()
65. تغییر اندازه تصویر با Pillow
img = img.resize((100, 100))
66. ذخیره تصویر تغییر یافته
img.save("small.jpg")
67. استفاده از moviepy برای ویرایش ویدئو
from moviepy.editor import VideoFileClip clip = VideoFileClip("video.mp4") clip.subclip(0, 10).write_videofile("short.mp4")
68. استفاده از tqdm برای نوار پیشرفت
from tqdm import tqdm for i in tqdm(range(100)): pass
69. استفاده از rich برای چاپ رنگی
from rich import print print("[bold red]Error[/bold red]")
70. استفاده از pyttsx3 برای تبدیل متن به گفتار
import pyttsx3 engine = pyttsx3.init() engine.say("Hello") engine.runAndWait()
71. استفاده از SpeechRecognition برای تبدیل گفتار به متن
import speech_recognition as sr
72. استفاده از beautifulsoup برای استخراج داده HTML
from bs4 import BeautifulSoup soup = BeautifulSoup("<p>Hello</p>", "html.parser")
73. پیدا کردن تگ‌ها با BeautifulSoup
soup.find("p").text
74. استفاده از flask برای ساخت API
from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello"
75. اجرای سرور Flask
flask run
بخش ۴ – ساخت پکیج اختصاصی (سوال 76 تا 100)
76. ساخت پوشه پکیج
my_package/ __init__.py module1.py
77. محتوای init.py
from .module1 import func
78. ساخت یک تابع در module1.py
def func(): print("From module1")
79. ایمپورت پکیج در برنامه اصلی
import my_package my_package.func()
80. ساخت پکیج چند سطحی
my_package/ sub_package/ __init__.py
81. استفاده از setup.py برای نصب پکیج
from setuptools import setup, find_packages setup(name="my_package", packages=find_packages())
82. نصب پکیج محلی
pip install .
83. ساخت فایل README برای پکیج
# My Package This package does amazing things.
84. استفاده از requirements.txt
requests pandas
85. نصب همه وابستگی‌ها از فایل
pip install -r requirements.txt
86. استفاده از virtualenv برای محیط مجازی
python -m venv env
87. فعال‌سازی محیط مجازی (ویندوز)
env\Scripts\activate
88. فعال‌سازی محیط مجازی (لینوکس/مک)
source env/bin/activate
89. خروج از محیط مجازی
deactivate
90. استفاده از poetry برای مدیریت پکیج‌ها
poetry init
91. اضافه کردن پکیج با poetry
poetry add requests
92. قفل کردن نسخه‌های پکیج
pip freeze > requirements.txt
93. نصب نسخه دقیق پکیج
pip install requests==2.28.1
94. حذف پکیج
pip uninstall requests
95. جستجوی پکیج در PyPI
pip search flask
96. استفاده از importlib.metadata برای نسخه پکیج
import importlib.metadata print(importlib.metadata.version("requests"))
97. لیست کردن همه پکیج‌ها
pip list
98. نصب پکیج از GitHub
pip install git+https://github.com/user/repo.git
99. استفاده از بسته zip نصب‌شده
pip install mypackage.zip
100. ساخت و آپلود پکیج در PyPI
python setup.py sdist twine upload dist/*
فصل کار با داده‌ها (Data Manipulation)
1. شمارش تعداد کاراکتر در رشته
text = "Python" print(len(text))
2. تغییر به حروف بزرگ
print("python".upper())
3. تغییر به حروف کوچک
print("PYTHON".lower())
4. اولین حرف بزرگ هر کلمه
print("hello world".title())
5. حذف فاصله‌های اضافی ابتدا و انتها
print(" hello ".strip())
6. جایگزینی یک کلمه در متن
print("I like Java".replace("Java", "Python"))
7. شمارش تعداد یک کلمه
print("python python java".count("python"))
8. بررسی وجود یک کلمه
print("python" in "I like python programming")
9. بررسی شروع شدن رشته با کلمه خاص
print("python programming".startswith("python"))
10. بررسی پایان یافتن رشته با کلمه خاص
print("python programming".endswith("programming"))
11. تقسیم رشته بر اساس فاصله
print("a b c".split())
12. ترکیب لیست رشته‌ها با جداکننده
print("-".join(["2025", "08", "14"]))
13. پیدا کردن موقعیت اولین occurrence
print("hello python".find("python"))
14. پیدا کردن موقعیت آخرین occurrence
print("python python".rfind("python"))
15. بررسی فقط عدد بودن رشته
print("12345".isdigit())
16. بررسی فقط حروف بودن رشته
print("Hello".isalpha())
17. بررسی ترکیب حروف و اعداد
print("Hello123".isalnum())
18. حذف همه فاصله‌ها در متن
print("a b c".replace(" ", ""))
19. برعکس کردن متن
print("python"[::-1])
20. شمارش تعداد حروف یونیک در متن
print(len(set("banana")))
21. مجموع یک لیست عددی

print(sum([1, 2, 3, 4]))

22. میانگین یک لیست عددی

nums = [1, 2, 3, 4]
print(sum(nums) / len(nums))

23. بزرگ‌ترین عدد در لیست

print(max([3, 8, 5]))

24. کوچک‌ترین عدد در لیست

print(min([3, 8, 5]))

25. پیدا کردن قدرمطلق یک عدد

print(abs(-10))

26. گرد کردن به عدد صحیح

print(round(4.7))

27. گرد کردن با تعداد اعشار خاص

print(round(3.14159, 2))

28. توان رساندن عدد

print(pow(2, 3))

29. ریشه دوم عدد

import math
print(math.sqrt(16))

30. محاسبه فاکتوریل

import math
print(math.factorial(5))

31. پیدا کردن عدد تصادفی بین دو عدد

import random
print(random.randint(1, 10))

32. انتخاب تصادفی یک عضو از لیست

import random
print(random.choice(["apple", "banana", "cherry"]))

33. مرتب‌سازی لیست عددی

nums = [5, 2, 9, 1]
nums.sort()
print(nums)

34. مرتب‌سازی نزولی

nums = [5, 2, 9, 1]
nums.sort(reverse=True)
print(nums)

35. محاسبه مجموع مربعات اعداد

nums = [1, 2, 3]
print(sum(x**2 for x in nums))

36. پیدا کردن مد (mode) داده‌ها

from statistics import mode
print(mode([1, 2, 2, 3]))

37. پیدا کردن میانه (median)

from statistics import median
print(median([1, 3, 2]))

38. پیدا کردن واریانس

from statistics import variance
print(variance([2, 4, 6, 8]))

39. پیدا کردن انحراف معیار

from statistics import stdev
print(stdev([2, 4, 6, 8]))

40. نرمال‌سازی داده‌ها به بازه 0 تا 1

nums = [10, 20, 30]
min_val, max_val = min(nums), max(nums)
normalized = [(x - min_val) / (max_val - min_val) for x in nums]
print(normalized)


---

بخش ۳ – پردازش لیست‌ها و دیکشنری‌ها (سوال 41 تا 60)

41. حذف تکراری‌ها از لیست

nums = [1, 2, 2, 3]
print(list(set(nums)))

42. شمارش عناصر با Counter

from collections import Counter
print(Counter(["a", "b", "a", "c"]))

43. مرتب‌سازی دیکشنری بر اساس کلید

data = {"b": 2, "a": 1}
print(dict(sorted(data.items())))

44. مرتب‌سازی دیکشنری بر اساس مقدار

data = {"b": 2, "a": 1}
print(dict(sorted(data.items(), key=lambda x: x[1])))

45. ترکیب دو لیست به صورت جفت

names = ["Ali", "Sara"]
ages = [25, 30]
print(list(zip(names, ages)))

46. تبدیل دو لیست به دیکشنری

names = ["Ali", "Sara"]
ages = [25, 30]
print(dict(zip(names, ages)))

47. فیلتر عناصر بزرگ‌تر از 10

nums = [5, 12, 7, 20]
print(list(filter(lambda x: x > 10, nums)))

48. اعمال تابع روی همه عناصر

nums = [1, 2, 3]
print(list(map(lambda x: x**2, nums)))

49. ادغام دو دیکشنری

a = {"x": 1}
b = {"y": 2}
print({a, b})

50. دیکشنری با مقادیر پیش‌فرض

from collections import defaultdict
d = defaultdict(int)
d["apple"] += 1
print(d)

51. حذف مقدار None از دیکشنری

data = {"a": 1, "b": None}
print({k: v for k, v in data.items() if v is not None})

52. پیدا کردن بیشترین مقدار دیکشنری

data = {"a": 10, "b": 5}
print(max(data, key=data.get))

53. گروه‌بندی داده‌ها با groupby

from itertools import groupby
data = sorted(["apple", "apricot", "banana"])
for k, g in groupby(data, key=lambda x: x[0]):
print(k, list(g))

54. معکوس کردن کلید و مقدار دیکشنری

data = {"a": 1, "b": 2}
print({v: k for k, v in data.items()})

55. بررسی وجود مقدار خاص در دیکشنری

data = {"a": 1, "b": 2}
print(2 in data.values())

56. ایجاد لیست از 1 تا 10

print(list(range(1, 11)))

57. ضرب همه عناصر لیست

import math
print(math.prod([1, 2, 3, 4]))

58. لیست comprehension برای توان دو

print([x**2 for x in range(5)])

59. لیست comprehension با شرط

print([x for x in range(10) if x % 2 == 0])

60. صاف کردن لیست تو در تو

nested = [[1, 2], [3, 4]]
print([x for sub in nested for x in sub])


---

بخش ۴ – پردازش داده‌های فایل و فرمت‌ها (سوال 61 تا 80)

61. خواندن CSV به لیست دیکشنری‌ها

import csv
with open("data.csv") as f:
reader = csv.DictReader(f)
print(list(reader))

62. نوشتن دیکشنری‌ها در CSV

import csv
rows = [{"name": "Ali", "age": 25}, {"name": "Sara", "age": 30}]
with open("data.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age"])
writer.writeheader()
writer.writerows(rows)

63. خواندن JSON

import json
with open("data.json") as f:
print(json.load(f))

64. نوشتن JSON با indent

import json
data = {"name": "Ali", "age": 25}
with open("data.json", "w") as f:
json.dump(data, f, indent=4)