Python Foundations & Workflow
Installing Python
Windows:
# Download from python.org
# Or use winget
winget install Python.Python.3.11
পাইথন ইনস্টল করার পর টার্মিনালে python --version লিখে চেক করুন যে সঠিকভাবে ইনস্টল হয়েছে কিনা।
Python Data Types & Variables
Basic Data Types / মৌলিক ডেটা টাইপ
- Integer: যেকোনো পূর্ণ সংখ্যা (১, ২, ১০০, -৫)
- Float: দশমিক সংখ্যা (৩.১৪, ৫.৯)
- String: টেক্সট বা লেখা ("নাম", "Hello")
- Boolean: শুধু দুটি মান থাকতে পারে - True অথবা False
# Integer (পূর্ণসংখ্যা)
age = 25
print(type(age)) # <class 'int'>
# Float (দশমিক সংখ্যা)
height = 5.9
print(type(height)) # <class 'float'>
# String (স্ট্রিং/টেক্সট)
name = "আহমেদ" # Bengali text supported
print(type(name)) # <class 'str'>
# Boolean (সত্য/মিথ্যা)
is_student = True
print(type(is_student)) # <class 'bool'>
# None (কিছুই নেই)
result = None
print(type(result)) # <class 'NoneType'>
Lists & Dictionaries (Important for ML)
Lists / লিস্ট
- লিস্ট হলো একাধিক ডেটা একসাথে রাখার উপায়
- লিস্টের ইনডেক্স শূন্য (০) থেকে শুরু হয়
- নেগেটিভ ইনডেক্স (-1) দিয়ে শেষ থেকে অ্যাক্সেস করা যায়
# Creating lists (লিস্ট তৈরি)
numbers = [1, 2, 3, 4, 5]
names = ["রহিম", "করিম", "সালমা"]
mixed = [1, "hello", 3.14, True]
# Accessing elements (এলিমেন্ট অ্যাক্সেস)
print(numbers[0]) # 1 (প্রথম এলিমেন্ট)
print(numbers[-1]) # 5 (শেষ এলিমেন্ট)
# Slicing (স্লাইসিং)
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3] (প্রথম তিনটি)
print(numbers[2:]) # [3, 4, 5] (তৃতীয় থেকে শেষ পর্যন্ত)
# List operations
numbers.append(6) # শেষে যোগ করা
numbers.insert(0, 0) # নির্দিষ্ট স্থানে যোগ করা
numbers.remove(3) # নির্দিষ্ট মান মুছে ফেলা
numbers.pop() # শেষ এলিমেন্ট মুছে ফেলা
# List comprehension (খুবই শক্তিশালী!)
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]
Dictionaries / ডিকশনারি
- ডিকশনারি হলো key-value পেয়ার
- প্রতিটি key এর বিপরীতে একটি value থাকে
- key দিয়ে খুব দ্রুত value খুঁজে পাওয়া যায়
# Creating dictionary (ডিকশনারি তৈরি)
student = {
"name": "আহমেদ",
"age": 22,
"cgpa": 3.85,
"subjects": ["Math", "Physics", "CS"]
}
# Accessing values (মান অ্যাক্সেস)
print(student["name"]) # আহমেদ
print(student.get("age")) # 22
# Adding/Updating (যোগ/আপডেট করা)
student["email"] = "ahmed@example.com"
student["age"] = 23
# Dictionary methods
keys = student.keys() # সব key পাওয়া
values = student.values() # সব value পাওয়া
items = student.items() # (key, value) pairs
# Dictionary comprehension
squared_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Control Flow (if/else, loops)
If-Else Statements
if-else দিয়ে শর্ত চেক করা যায় এবং সেই অনুযায়ী কোড চালানো যায়।
# Simple if-else
age = 20
if age >= 18:
print("আপনি প্রাপ্তবয়স্ক") # You are adult
else:
print("আপনি নাবালক") # You are minor
# Multiple conditions
marks = 85
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
else:
grade = "C"
print(f"Your grade: {grade}")
# Ternary operator (এক লাইনে if-else)
status = "Pass" if marks >= 50 else "Fail"
- for loop: নির্দিষ্ট সংখ্যকবার বা লিস্টের প্রতিটি আইটেমের জন্য চলে
- while loop: যতক্ষণ শর্ত সত্য ততক্ষণ চলতে থাকে
- break: লুপ থামিয়ে দেয়
- continue: বর্তমান ইটারেশন স্কিপ করে পরেরটিতে যায়
For Loops / ফর লুপ
# Basic for loop
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Loop through list
fruits = ["আম", "কলা", "জাম"]
for fruit in fruits:
print(fruit)
# Loop with index and value
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Range with start, stop, step
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
While Loops / হোয়াইল লুপ
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1
# Break and continue
for i in range(10):
if i == 3:
continue # Skip 3
if i == 7:
break # Stop at 7
print(i)
Functions / ফাংশন
Defining Functions
- ফাংশন হলো পুনরায় ব্যবহারযোগ্য কোড ব্লক
-
defদিয়ে ফাংশন তৈরি করা হয় -
returnদিয়ে ফাংশন থেকে মান ফেরত পাঠানো হয় -
*args: যেকোনো সংখ্যক আর্গুমেন্ট নেয় -
**kwargs: যেকোনো সংখ্যক keyword আর্গুমেন্ট নেয়
# Basic function
def greet(name):
"""এই ফাংশন একটি নাম নিয়ে শুভেচ্ছা বার্তা দেয়"""
return f"Hello, {name}!"
message = greet("আহমেদ")
print(message) # Hello, আহমেদ!
# Multiple parameters
def add(a, b):
"""দুটি সংখ্যা যোগ করে"""
return a + b
result = add(5, 3)
print(result) # 8
# Default arguments
def power(base, exponent=2):
"""একটি সংখ্যার ঘাত বের করে (ডিফল্ট ঘাত = ২)"""
return base ** exponent
print(power(3)) # 9 (3^2)
print(power(3, 3)) # 27 (3^3)
# *args - variable number of arguments
def sum_all(*numbers):
"""যেকোনো সংখ্যক সংখ্যা যোগ করে"""
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
# **kwargs - keyword arguments
def student_info(**info):
"""Student information প্রিন্ট করে"""
for key, value in info.items():
print(f"{key}: {value}")
student_info(name="রহিম", age=22, cgpa=3.7)
Lambda Functions (Anonymous Functions)
# Regular function
def square(x):
return x ** 2
# Lambda equivalent (এক লাইনে)
square_lambda = lambda x: x ** 2
print(square(5)) # 25
print(square_lambda(5)) # 25
# Lambda with multiple arguments
add = lambda a, b: a + b
print(add(3, 5)) # 8
# Used with map, filter
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16, 25]
even = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4]
File Handling (CSV read/write, Pathlib)
-
with open()ব্যবহার করলে ফাইল অটোমেটিক বন্ধ হয়ে যায় -
'r'= read (পড়া),'w'= write (লেখা),'a'= append (যোগ করা) -
encoding='utf-8'বাংলা টেক্সটের জন্য জরুরি - Pathlib আধুনিক এবং ক্রস-প্ল্যাটফর্ম উপায়
Reading Files / ফাইল পড়া
# Basic file reading
with open('data.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
# Read line by line
with open('data.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip()) # strip() removes \n
# Read all lines into a list
with open('data.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
Writing Files / ফাইলে লেখা
# Write mode (overwrites existing file)
with open('output.txt', 'w', encoding='utf-8') as file:
file.write("Hello, World!\n")
file.write("নমস্কার, পৃথিবী!\n")
# Append mode (adds to existing file)
with open('output.txt', 'a', encoding='utf-8') as file:
file.write("New line added\n")
Working with CSV Files
import csv
# Reading CSV
with open('students.csv', 'r', encoding='utf-8') as file:
csv_reader = csv.reader(file)
# Skip header
next(csv_reader)
for row in csv_reader:
name, age, cgpa = row
print(f"{name}: {cgpa}")
# Writing CSV
students = [
["Name", "Age", "CGPA"],
["আহমেদ", 22, 3.85],
["রহিম", 21, 3.70],
["সালমা", 23, 3.92]
]
with open('students.csv', 'w', encoding='utf-8', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(students)
# Using DictReader/DictWriter (recommended)
with open('students.csv', 'r', encoding='utf-8') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
print(row['Name'], row['CGPA'])
Using Pathlib (Modern approach)
from pathlib import Path
# Create Path object
data_dir = Path('data')
file_path = data_dir / 'students.csv'
# Check if exists
if file_path.exists():
print("File exists")
# Create directory
data_dir.mkdir(exist_ok=True)
# Read file
content = file_path.read_text(encoding='utf-8')
# Write file
file_path.write_text("New content", encoding='utf-8')
# Get file info
print(file_path.name) # students.csv
print(file_path.stem) # students
print(file_path.suffix) # .csv
print(file_path.parent) # data
8. Exception Handling / এক্সেপশন হ্যান্ডলিং
-
try: যে কোড এরর দিতে পারে তা এখানে রাখি -
except: এরর হলে এই কোড চলবে -
finally: এরর হোক বা না হোক এই কোড চলবে -
raise: নিজে এরর তৈরি করা
# Basic try-except
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("দয়া করে একটি সংখ্যা লিখুন!")
except ZeroDivisionError:
print("শূন্য দিয়ে ভাগ করা যায় না!")
# Multiple exceptions
try:
file = open('data.txt', 'r')
content = file.read()
value = int(content)
except (FileNotFoundError, ValueError) as e:
print(f"Error occurred: {e}")
finally:
file.close() # Always executes
# Raising exceptions
def calculate_percentage(marks, total):
if total == 0:
raise ValueError("Total cannot be zero")
return (marks / total) * 100
try:
percentage = calculate_percentage(85, 0)
except ValueError as e:
print(f"Error: {e}")
Logging Basics (Debugging Setup)
লগিং ব্যবহার করে প্রোগ্রামের কি হচ্ছে তা ট্র্যাক করা যায়, যা ডিবাগিংয়ে খুব সাহায্য করে।
import logging
# Basic logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.debug("এটি একটি debug message")
logging.info("এটি একটি info message")
logging.warning("এটি একটি warning message")
logging.error("এটি একটি error message")
logging.critical("এটি একটি critical message")
# Logging to file
logging.basicConfig(
filename='app.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.info("Application started")
Mini-Project: CSV Data Cleaner
import csv
from pathlib import Path
def clean_csv(input_file, output_file):
"""
CSV file থেকে empty rows এবং duplicate rows মুছে ফেলে
Args:
input_file: Input CSV file path
output_file: Output CSV file path
"""
# Read data
with open(input_file, 'r', encoding='utf-8') as file:
reader = csv.DictReader(file)
rows = list(reader)
# Remove empty rows
cleaned_rows = [row for row in rows if any(row.values())]
# Remove duplicates
seen = set()
unique_rows = []
for row in cleaned_rows:
row_tuple = tuple(row.items())
if row_tuple not in seen:
seen.add(row_tuple)
unique_rows.append(row)
# Write cleaned data
if unique_rows:
with open(output_file, 'w', encoding='utf-8', newline='') as file:
writer = csv.DictWriter(file, fieldnames=unique_rows[0].keys())
writer.writeheader()
writer.writerows(unique_rows)
print(f"✓ Cleaned {len(rows)} rows → {len(unique_rows)} unique rows")
print(f"✓ Saved to {output_file}")
# Usage
clean_csv('dirty_data.csv', 'clean_data.csv')
Key Takeaways
- ✓ Python এর মৌলিক syntax এবং data types
- ✓ List, Dictionary ব্যবহার করে data organize করা
- ✓ Control flow দিয়ে logic তৈরি করা
- ✓ Function লিখে reusable code তৈরি করা
- ✓ File handling দিয়ে data read/write করা
- ✓ Exception handling দিয়ে error handle করা
Top comments (0)