পাঠ ০২ · ২৫-এর মধ্যে · মডিউল ১

Variable, ডেটা টাইপ ও অপারেটর

Variables, types & operators
৬ মিনিট পড়া শুরু · Beginner ব্রাউজারে কোড চালান

এই পাঠে যা শিখবেন

  • Variable কীভাবে তৈরি ও পরিবর্তন হয় — Python-এর memory model
  • চারটি মৌলিক ডেটা টাইপ ও তাদের ব্যবহার
  • Type conversion — int(), float(), str()
  • গাণিতিক, তুলনা ও যৌক্তিক operator
  • f-string দিয়ে সুন্দর output তৈরি

১ · Variable — তথ্য রাখার বাক্স

একটি variableVariableমেমোরির একটি অবস্থানের নামকরা reference. মান ধারণ করে — বদলানো যায়। Python-এ variable একটি object-এর label মাত্র। হলো মেমোরির একটি জায়গার "নাম"। যেমন একটি বাক্সে নাম-ট্যাগ লাগানো — পরে নাম বললেই বাক্সটা পাওয়া যায়।

Assignment-এর তিন নিয়ম

১) x = 5 — Python-এ "x = 5"-কে বলে assignment, "x সমান ৫" নয়।
২) ডান দিক আগে evaluate হয় — তারপর বাঁ দিকে রাখা হয়।
৩) একই variable পরে অন্য মান ধরতে পারে — x = 10 তখন ৫ উপড়ে গেল।

Python
# Variable তৈরি ও পরিবর্তন
age = 25
print("বয়স:", age)

age = age + 1   # বাঁ দিকের age = ডান দিকের (পুরনো age + 1)
print("পরের বছর:", age)

name = "রহিম"
city = "ঢাকা"
print(name, "থাকে", city, "শহরে")

    
age = age + 1 — গণিতের চোখে অসম্ভব, কিন্তু programming-এ "নতুন age = পুরনো age + 1"। সমার্থ লিখন: age += 1।

২ · নামকরণের নিয়ম

  • অক্ষর/আন্ডারস্কোর দিয়ে শুরু: name, _temp ✓   2name ✗
  • সংখ্যা, অক্ষর, _ চলে: age_2024 ✓
  • case-sensitive: Age ≠ age
  • reserved word নয়: if, for, class ব্যবহার করা যাবে না।
Variable name = মুদির দোকানের জারের লেবেল। x, y, tmp — ভেতরে কী আছে বোঝা যায় না। monthly_revenue — পড়লেই বোঝা। ৬ মাস পরে নিজে ফিরে আসবেন — তখন বুঝবেন কেন অর্থবহ নাম গুরুত্বপূর্ণ।

৩ · চারটি মৌলিক ডেটা টাইপ

Python-এ অসংখ্য type — কিন্তু শুরুতে চারটি যথেষ্ট:

Python
# চার মৌলিক type
count = 42                # int — পূর্ণসংখ্যা
price = 99.50             # float — দশমিক
name = "ABCL TECH"        # str — টেক্সট
is_active = True          # bool — True/False

print(count, type(count))
print(price, type(price))
print(name, type(name))
print(is_active, type(is_active))

    
type() function variable-এর ধরন বলে। Python dynamically typed — আপনি ঘোষণা করেন না, Python ডান-পক্ষ দেখে নিজেই ঠিক করে।

৪ · Type conversion

User-এর কাছ থেকে input() দিয়ে নেওয়া সব value str। তাই গণনার আগে castType Castingএকটি type থেকে অন্য type-এ রূপান্তর। int("5") → 5, str(5) → "5"। AI-তে CSV-র string-কে number-এ রূপান্তর — সাধারণ কাজ। করতে হয়।

Python
# type রূপান্তর
text_num = "100"
real_num = int(text_num)
print(real_num + 50)         # 150 — গণনা সম্ভব

# float থেকে int — দশমিক কেটে যায়
print(int(3.7))              # 3, রাউন্ড নয়

# int থেকে str
score = 85
msg = "তোমার স্কোর: " + str(score)
print(msg)

    
int(3.7) দেয় ৩ — দশমিক কেটে দেয় (truncation), রাউন্ড করে না। রাউন্ড করতে round(3.7) দরকার।
Python ডেটা টাইপ ও অপারেটর Types meet operators int পূর্ণসংখ্যা 5, -10, 0 float দশমিক 3.14, -0.5 str টেক্সট "hello" bool সত্য/মিথ্যা True, False Operator-এর সাথে যা যা সম্ভব গাণিতিক + - * / // % ** int + int → int int + float → float str + str → str (concat) str * int → repeat তুলনা ও যৌক্তিক == != < > <= >= and or not → সবসময় bool ফেরত if/while-এ সিদ্ধান্ত নিতে Type ও operator-এর match — Python-এর core
চারটি type আর তাদের সাথে কী কী operator চলে — Python-এর দৈনন্দিন কাজের ভিত্তি।

৫ · গাণিতিক operator

Python
a = 17
b = 5

print("যোগ:", a + b)          # 22
print("বিয়োগ:", a - b)        # 12
print("গুণ:", a * b)           # 85
print("ভাগ:", a / b)           # 3.4 — সবসময় float
print("পূর্ণ ভাগ:", a // b)    # 3 — দশমিক কেটে দেয়
print("ভাগশেষ:", a % b)        # 2
print("ঘাত:", a ** 2)          # 289 — a²

    
/ সবসময় float দেয় (Python ৩-এর সিদ্ধান্ত)। পূর্ণসংখ্যা ভাগ চাইলে //। AI-তে % দিয়ে — "প্রতি ১০টি batch-এ একবার log রাখো" এই ধরনের কাজ।

৬ · তুলনা ও যৌক্তিক operator

Python
age = 22

# তুলনা — bool ফেরত
print(age == 18)        # False — সমান কি?
print(age != 18)        # True — অসমান কি?
print(age >= 18)        # True — ১৮ বা বেশি?

# যৌক্তিক — শর্ত যোগ
has_id = True
print(age >= 18 and has_id)        # দু'টোই True
print(age < 18 or has_id)          # একটা True হলেই
print(not has_id)                  # উল্টানো

    
মনে রাখুন: = = assignment ("রাখো"), == = equality test ("সমান কি?")। এই দু'টো গুলিয়ে ফেলা — Python নবীনদের সবচেয়ে সাধারণ ভুল।

৭ · f-string — সুন্দর output

Python 3.6 (২০১৬) থেকে f-stringf-string"formatted string literal" — string-এর ভেতরে directly variable insert। f"{x}" = str(x)। দ্রুত, পাঠযোগ্য, আজকের default। — string-এর ভেতরে directly variable লেখার সবচেয়ে সরল উপায়।

Python
name = "ফাতেমা"
score = 92.567
total = 100

# f-string — শুরুতে f, ভেতরে {}
print(f"{name}-র স্কোর {score}/{total}")
print(f"শতকরা: {score/total*100:.1f}%")    # ১ দশমিক

# পুরনো পদ্ধতি — কম পঠনযোগ্য
print(name + "-র স্কোর " + str(score))

    
{score:.1f} মানে — "score-কে ১ দশমিক স্থান-এ float হিসেবে লিখো"। AI-তে loss/accuracy print-এ এটা অপরিহার্য।

৮ · AI-তে এই ধারণার ব্যবহার

  • Hyperparameter: learning_rate = 0.001 — float variable।
  • Dataset size: n_samples = 60000 — int।
  • Model name: model = "BERT-base" — str।
  • Training flag: is_training = True — bool, dropout/batch-norm-এ লাগে।
  • Logging: print(f"Epoch {e}: loss={loss:.4f}") — f-string আদর্শ।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ Python "dynamically typed" — type ঘোষণা করতে হয় না। C/Java-তে int x = 5 বাধ্যতামূলক। কোনটা ভালো? AI-তে কোন আঘাতগুলো type-error থেকে আসে?

Static বনাম dynamic typing — programming language design-এর সবচেয়ে পুরনো বিতর্কগুলোর একটি। কোনো একটি সমাধান "সঠিক" নয় — context-নির্ভর।

Dynamic typing-এর সুবিধা (Python):

  • সরল syntax — শেখা সহজ, লিখতে দ্রুত।
  • Prototype দ্রুত — গবেষণা ও notebook-এ অপরিহার্য।
  • Duck typing — "যদি duck-এর মতো হাঁটে ও ডাকে, তবে duck"। Polymorphism free।
  • Refactor — type পরিবর্তন করতে এক জায়গায়।

Static typing-এর সুবিধা (Java/Rust/Go):

  • Compile-time error — production-এ পৌঁছানোর আগে।
  • IDE autocomplete নিখুঁত।
  • Performance — JIT/AOT compiler optimize করতে পারে।
  • Self-documenting — function signature দেখে কাজ বুঝা যায়।

AI-তে type-error-এর ক্ষতি:

  • Silent type promotion: int + float → float। GPU memory ৪ গুণ বেড়ে যেতে পারে।
  • Tensor shape mismatch: (3, 4) vs (4, 3) — runtime error, সময় নষ্ট।
  • String vs number: CSV থেকে "5" বনাম 5 — model-এ feed করলে crash।
  • None propagation: NumPy-তে None পেলে NaN — পুরো dataset corrupt।
  • Bool vs int: True + True == 2 — Python-এ bool সম্প্রসারিত int।

Python-এর হাইব্রিড সমাধান — type hints (২০১৪ থেকে):

def predict(x: np.ndarray, model: nn.Module) -> torch.Tensor:
    ...
  • Runtime-এ ignore — performance impact নেই।
  • mypy, pyright — static checker। CI-তে চালালে compile-time-এর মতো নিরাপত্তা।
  • VS Code/PyCharm autocomplete নিখুঁত।
  • Pydantic — runtime type validation, FastAPI-র মূল।

Modern best practice:

  • Library/production code — type hints বাধ্যতামূলক।
  • Notebook/exploration — skip allowed।
  • Public API — Pydantic বা TypedDict ব্যবহার।

মূল উপলব্ধি: Python-এর type system "duck-with-receipts" — runtime flexible, optional static check। সঠিকভাবে ব্যবহার করলে — best of both। AI কাজে type discipline = bug-free model।

প্র ০২ Float-এ 0.1 + 0.2 == 0.3 কেন False দেয়? এটা bug না feature? AI-তে এই floating-point precision সমস্যা কোথায় কামড় দেয়?

Floating-point arithmetic — কম্পিউটার বিজ্ঞানের ক্লাসিক "gotcha"। প্রায় সব ভাষায় এই behavior। কারণ — মৌলিক, ভাষার সমস্যা নয়।

কারণ — IEEE 754 standard (১৯৮৫):

  • কম্পিউটার সংখ্যা রাখে binary-তে — ২-এর ঘাতের যোগফল।
  • 0.1 = 1/10 — binary-তে অনন্ত repeating: 0.0001100110011...
  • ৬৪-bit double — ~১৭ decimal digits-এ truncate।
  • 0.1 + 0.2 = 0.30000000000000004 (truncation jitter)।

সঠিক compare করার উপায়:

import math
math.isclose(0.1 + 0.2, 0.3)  # True

# অথবা — tolerance
abs(a - b) < 1e-9

AI-তে যেখানে কামড় দেয়:

  • Loss == 0 check: কখনো নয়! loss < 1e-6।
  • Probability sum to 1: softmax output 0.999999... — round করতে হয়।
  • Reproducibility: GPU বনাম CPU-তে floating-point order ভিন্ন — slight ভিন্ন result।
  • Gradient near zero: overflow/underflow — log(0) = -inf, NaN propagation।
  • Mixed precision: fp16 (16-bit) মাত্র ~৩-৪ decimal digits — gradient vanishing/exploding।

Python-এর numerical stability tricks:

  • log-sum-exp trick: log(sum(exp(x))) overflow এড়াতে।
  • Decimal module: ব্যাঙ্কিং-এ। AI-তে rare।
  • Fractions module: exact rational। শিক্ষায় ভাল।
  • NumPy float64: default — সাধারণ AI কাজে যথেষ্ট।

AI-তে bf16 (Brain Float):

  • Google Brain (২০১৮) — 16-bit, fp32-এর দিগন্ত (range), fp16-এর precision।
  • LLM training-এ standard। মেমোরি অর্ধেক, accuracy কাছাকাছি।

মূল উপলব্ধি: Float "feature" — কম মেমোরি ও দ্রুত গণনার trade-off। AI engineer-কে precision-এর সীমা জানতে হবে। == দিয়ে float compare করবেন না — কখনো।

প্র ০৩ Python-এ a = [1, 2]; b = a; b.append(3) করলে a-ও বদলায়। কেন? "Pass by reference" বনাম "pass by value" — Python কোন দলে?

Python-এর memory model — beginners-এর সবচেয়ে confusing topic। সঠিক উত্তর: Python "pass by object reference" (বা "pass by assignment") — দু'টোর কোনোটা নয়।

মূল ধারণা:

  • Python-এ variable হলো object-এর "label" বা "name tag"।
  • a = [1, 2] — মেমোরিতে list object তৈরি, a তার tag।
  • b = a — একই object-এ আরেকটি tag, copy নয়।
  • b.append(3) — object বদলে গেল; দু'টি tag-ই দেখে নতুন object।

Mutable vs Immutable type:

  • Immutable: int, float, str, tuple, frozenset, bool — পরিবর্তন করা যায় না।
  • Mutable: list, dict, set, custom class — পরিবর্তন করা যায়।
  • Immutable-এ "reassign" নতুন object তৈরি করে — পুরনো link ভাঙে।

চিত্র দিয়ে বোঝা:

a = [1, 2]      # a → [1, 2]  (object id: 100)
b = a           # a, b → [1, 2]  (id: 100)
b.append(3)     # a, b → [1, 2, 3]  (id: 100, mutated)
print(id(a) == id(b))  # True

# কিন্তু int-এ
x = 5           # x → 5 (id: 200)
y = x           # x, y → 5 (id: 200)
y = y + 1       # y → 6 (new id: 201), x still 5

Function-এ এর প্রভাব:

def add_item(lst):
    lst.append("new")    # caller-এর list-ও বদলায়

def increment(n):
    n = n + 1            # local — caller-এর n বদলায় না

সঠিক copy করার উপায়:

  • Shallow copy: b = a.copy() বা b = a[:] বা list(a)।
  • Deep copy: import copy; b = copy.deepcopy(a) — nested list-ও copy।

AI-তে এই concept-এর তাৎপর্য:

  • NumPy array: b = a view, পরিবর্তন shared। b = a.copy() independent।
  • PyTorch tensor: x.clone() — gradient graph থেকেও বিচ্ছিন্ন করতে .detach().clone()।
  • Dataset augmentation: in-place vs new tensor — bug-prone।
  • Hyperparameter dict: default mutable arg — ক্লাসিক bug।

মূল উপলব্ধি: Python-এ "নাম ≠ বস্তু"। বুঝলে — debug-এ ৫০% সময় বাঁচে। NumPy/PyTorch-এর সব memory bug এই ভিত্তিতে দাঁড়িয়ে।

প্র ০৪ Variable নামকরণে কোন convention অনুসরণ করা উচিত? snake_case, camelCase, PascalCase — কখন কোনটা? AI কোডে কেন বিশেষ গুরুত্ব?

Naming conventions কোডের soul। ভুল নাম = ৬ মাস পরে নিজের কোড পড়ে boggle-এ পড়া।

Python-এর official guide — PEP 8 (২০০১):

  • snake_case — variables, functions, modules। ex: train_data, get_score()।
  • PascalCase — class। ex: NeuralNetwork, DataLoader।
  • UPPER_SNAKE — constants। ex: BATCH_SIZE = 32।
  • _leading_underscore — "private" (convention only)।
  • __double_underscore__ — Python's special methods, কখনো নিজে ব্যবহার নয়।

AI কোডে অতিরিক্ত conventions:

  • X, y: features ও labels (scikit-learn ঐতিহ্য)। X_train, y_test।
  • x, y, z: tensor — neural network forward pass-এ।
  • n_ prefix — count। n_samples, n_features, n_epochs।
  • idx, i, j — index। loop-এ short ok।
  • logits, probs — model output stages।
  • loss, acc — training metric।

খারাপ নামের মূল্য:

  • data, data2, data_new, final_data — কে আসল?
  • x ১০০ লাইনের scope-এ — অর্থহীন।
  • l, I, O — 1, 0-এর সাথে গুলিয়ে যায়।
  • tmp, foo, bar — production-এ চলবে না।

সাফল্যের সূত্র — "Stockholm Test":

  • Variable-টা স্কোপের বাইরে গুগল করতে হলো? — নাম খুব short।
  • প্রথম দেখায় বুঝতে comment লাগল? — নাম misleading।
  • রিভিউয়ার "এটা কী?" জিজ্ঞেস করল? — নাম obscure।

সংক্ষিপ্ত vs দীর্ঘ — context-নির্ভর:

  • Local loop variable — i ok।
  • Function parameter — learning_rate, n_layers।
  • Global constant — DEFAULT_BATCH_SIZE।
  • Class attribute — self.embedding_dim।

মূল উপলব্ধি: "Code is read 10 times more than written." — Robert C. Martin. ভাল নামকরণ = ভবিষ্যৎ আমাকে দেওয়া উপহার। AI কোডে — যেখানে paper থেকে paper জুড়ে diversion — convention কঠোরভাবে মানলে collaboration ১০× সহজ।

অনুশীলন

  1. BMI ক্যালকুলেটর: ওজন (kg) ও উচ্চতা (m) variable নিয়ে BMI হিসাব করুন। সূত্র: $\text{BMI} = \text{ওজন} / \text{উচ্চতা}^2$।
    weight_kg = 70
    height_m = 1.75
    bmi = weight_kg / (height_m ** 2)
    print(f"BMI: {bmi:.2f}")
    # Output: BMI: 22.86
  2. Type guess: type(5/2), type(5//2), type("5"+"2"), type(True+True) — প্রতিটির output আগে অনুমান করে তারপর চালান।
    • 5/2 = 2.5 → float
    • 5//2 = 2 → int
    • "5"+"2" = "52" → str (concatenation, not addition)
    • True+True = 2 → int (bool extends int)
  3. ভাবুন: একজন AI মডেলের accuracy ০.৮৭৫৪৩২। সেটা ২ দশমিক স্থানে percentage হিসেবে print করুন f-string দিয়ে।
    accuracy = 0.875432
    print(f"Accuracy: {accuracy*100:.2f}%")
    # Output: Accuracy: 87.54%

আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ

কোড রানার কাজ না করলে? ব্রাউজারে কাজ না করলে Google Colab ব্যবহার করুন — Google-এর ফ্রি অনলাইন Python পরিবেশ, শুধু Gmail অ্যাকাউন্ট লাগে।
পূর্ববর্তী পাঠ
পাঠ ০১ · Python সেটআপ ও Hello World