Python syntax, data types, control flow
1.4.1· AI-ML › Python & Scientific Computing
Why Python for AI/ML?
Python AI/ML mein teen wajahon se dominate karta hai:
- Readable syntax → faster prototyping aur debugging
- Rich ecosystem → NumPy, Pandas, Scikit-learn, PyTorch, TensorFlow
- Dynamic typing → rapid experimentation (computational speed ki jagah development speed milti hai)
Dynamic typing ka matlab hai ki Python types ko runtime par check karta hai, compile-time par nahi. Yahi flexibility ki wajah se aap quickly ML hypotheses test kar sakte ho, lekin subtle bugs se bachne ke liye types ko deeply samajhna bhi zaroori hai.
Python Data Types: The Building Blocks
Why These Types Matter in ML
Integers aur Floats: Features, labels, hyperparameters represent karte hain. Float precision gradient descent mein numerical stability ko affect karti hai.
Lists vs Tuples: Lists mutable data ke liye (jaise predictions collect karna), tuples immutable configs ke liye (jaise input_shape=(28, 28, 1)).
Dictionaries: Model hyperparameters, config files, feature mappings store karte hain. Average lookup time O(1) hoti hai.
None: Imputation se pehle missing data represent karta hai, uninitialized model weights ke liye bhi.
Type Conversion aur Coercion
Python mein explicit type conversion hoti hai (operations mein numeric types ke beech automatic coercion nahi hoti jahan precision loss ho sake):
# Explicit conversions
x = int(3.7) # 3 (truncates, rounds nahi karta)
y = float("2.5") # 2.5
z = str(42) # "42"
# Mixed arithmetic most general type par promote karta hai
result = 5 + 2.0 # 7.0 (int + float → float)Explicit kyun? Silent precision loss bugs se bachata hai. ML mein accidentally float weights ko int mein convert karna model performance destroy kar deta.
Python Syntax: Indentation as Grammar
# Correct indentation
if accuracy > 0.95:
print("Model converged")
save_checkpoint() # if-block ka part hai
print("Training complete") # if-block ke bahar
# WRONG: Inconsistent indentation causes IndentationError
if accuracy > 0.95:
print("Model converged")
save_checkpoint() # ERROR: unexpected indentYeh design kyun? Readable code force karta hai. Teams mein share hone wale ML research code mein, consistent structure cognitive load kam karta hai.
Variables and Assignment
Python reference semantics use karta hai:
# Assignment ek reference banata hai, copy nahi
weights_original = [0.5, 0.3, 0.8]
weights_backup = weights_original # Dono SAME list ko point karte hain
weights_backup[0] = 0.9 # Original ko bhi modify kar deta hai!
print(weights_original) # [0.9, 0.3, 0.8]
# Correct: explicit copy
import copy
weights_backup = copy.deepcopy(weights_original)ML mein yeh kyun matter karta hai: Neural network layers aksar weight references share karti hain. Ek reference modify karne se sab affect hote hain jab tak explicitly copy na karo.
learning_rate = 0.01 # Global
def train_model():
learning_rate = 0.001 # Local (global ko shadow karta hai)
def update_weights():
# Enclosing function ka learning_rate use karta hai (0.001)
print(f"LR: {learning_rate}")
update_weights()
train_model() # Prints "LR: 0.001"Control Flow: Directing Computation
Conditional Statements
Python mein Truthiness: Objects ke inherent boolean values hote hain. Empty containers ([], {}, ""), 0, None falsy hain. Baaki sab truthy hain.
# Check karna ki list non-empty hai (Pythonic)
predictions = [0.9, 0.3, 0.7]
if predictions: # Truthy kyunki list non-empty hai
avg = sum(predictions) / len(predictions)Loops: For aur While
List Comprehensions: Iterables se lists banane ka concise syntax.
# Standard loop
squared = []
for x in range(10):
squared.append(x ** 2)
# List comprehension (Pythonic)
squared = [x ** 2 for x in range(10)]
# Condition ke saath (filter)
even_squared = [x ** 2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]
# Yeh kyun use karein? Zyada readable, aksar faster (optimized C implementation).
# Data preprocessing mein common: [preprocess(x) for x in dataset]Loop Control: Break aur Continue
break: Innermost loop se turant bahar nikal jaocontinue: Loop body ka bacha hua hissa skip karo, next iteration par jao
# Corrupted data samples skip karo
for i, sample in enumerate(dataset):
if is_corrupted(sample):
print(f"Skipping sample {i}")
continue # Next iteration par jump karo
if i >= max_samples:
break # Loop se poori tarah bahar nikal jao
process(sample)Functions: Encapsulation aur Reusability
Argument Passing
Python pass-by-object-reference use karta hai:
- Immutable objects (int, float, str, tuple): Pass-by-value jaisa behave karte hain (modify nahi ho sakte)
- Mutable objects (list, dict, set): Function ke andar modifications original ko affect karti hain
def modify_list(lst):
lst.append(4) # Original list modify karta hai
def modify_int(x):
x += 10 # Naya local int banata hai, original affect nahi hota
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # [1, 2, 3, 4]—modify ho gaya!
my_int = 5
modify_int(my_int)
print(my_int) # 5—unchangedML mein yeh kyun matter karta hai: Functions ko large arrays/tensors pass karne se data copy nahi hoti (efficient hai), lekin unexpected modifications bugs create kar sakti hain.
*args aur **kwargs
def train_model(model, data, *args, **kwargs):
"""
*args: Positional arguments as tuple
**kwargs: Keyword arguments as dict
"""
epochs = kwargs.get('epochs', 100) # Default 100
lr = kwargs.get('learning_rate', 0.01)
print(f"Extra args: {args}")
print(f"Extra kwargs: {kwargs}")
# Alag-alag arguments ke saath call karo
train_model(my_model, my_data, "extra", "values",
epochs=50, learning_rate=0.001, batch_size=32)
# args = ("extra", "values")
# kwargs = {'epochs': 50, 'learning_rate': 0.001, 'batch_size': 32}Use case: Flexible APIs banana (jaise Keras ka model.fit() jo bahut saare optional hyperparameters accept karta hai).
Exception Handling
EAFP vs LBYL: Python "Easier to Ask Forgiveness than Permission" (try-except) ko prefer karta hai "Look Before You Leap" (if checks) ke muqable mein. Python mein exceptions expensive nahi hote jab uncommon hon.
Comprehensions Beyond Lists
Dictionary Comprehension:
# Feature name se index mapping banao
feature_names = ['age', 'income', 'score']
feature_to_idx = {name: i for i, name in enumerate(feature_names)}
# {'age': 0, 'income': 1, 'score': 2}Set Comprehension:
# Dataset mein unique labels
labels = [0, 1, 0, 2, 1, 2]
unique_labels = {label for label in labels}
# {0, 1, 2}Generator Expression (memory-efficient, lazy evaluation):
# Bade dataset ko poora memory mein laade bina process karo
data_generator = (preprocess(x) for x in huge_dataset)
# Values iteration ke dauran on-demand compute hoti hain
for item in data_generator:
train_on(item)ML mein generators kyun? Jab dataset RAM mein fit nahi hota. TensorFlow ka tf.data aur PyTorch ka DataLoader yahi principle use karte hain.
Recall 12 saal ke bacche ko explain karo
Socho tum ek robot ko khana banana sikha rahe ho. Python instruction booklet ki language hai.
Data types ingredient categories jaisi hain: numbers (kitne ande), text (recipe ka naam), lists (shopping list jo change ho sakti hai), tuples (ingredient ratios jo kabhi nahi badalte).
Control flow recipe steps hain: "AGAR oven garam hai TO cake daal do, WARNA wait karo." Ya "HAR 12 cupcake ke liye, frosting lagao."
Functions sub-recipes hain: "mix flour, sugar, butter" baar baar likhne ki jagah ek "make_dough()" recipe banao jo reuse ho sake.
Indentation (lines se pehle wale spaces) dikhata hai ki kaunsi instructions saath hain—jaise recipe steps "Baking" ke neeche indent hoti hain us heading ke under.
ML mein, aap computers ko patterns seekhna sikha rahe ho. Python woh teaching instructions clearly dene ka tarika hai. Jaise recipes mein exact measurements chahiye, ML code mein exact data types chahiye. Jaise aap keh sakte ho "SMOOTH hone TAK mix karte raho," ML WHILE loops use karta hai tab TAK train karne ke liye jab TAK model kaafi achha na ho jaaye.
Connections NumPy arrays and vectorization - Python lists par built hai lekin numerical computation ke liye optimized
- Pandas DataFrames - Python dicts ko internally use karta hai, ML-focused data manipulation add karta hai
- Python functions and lambda - Function definition anonymous functions tak extend hoti hai
- Object-oriented programming in Python - Classes function aur scope concepts par build hoti hain
- TensorFlow and PyTorch basics - ML frameworks training loops ke liye Python control flow use karte hain
- Exception handling in data pipelines - Robust ML systems ke liye try-except patterns
- Python iterators and generators - Memory efficiency ke liye loop concepts extend karta hai
Practice Problems
- Ek function likho jo model predictions ki list le aur accuracy, precision, aur recall return kare.
- While loop se early stopping implement karo jo validation loss track kare.
- Ek dict comprehension banao jo neural network mein layer names ko parameter counts se map kare.
- Is code ko debug karo: Kyon function ke andar
layer_configmodify karne se original change ho jaata hai?

#flashcards/ai-ml
Variable resolution ke liye Python ka LEGB rule kya hai? :: Local → Enclosing → Global → Built-in. Python variable names resolve karne ke liye in scopes mein is order mein search karta hai.
Python braces ki jagah code blocks ke liye indentation kyun use karta hai?
Python mein = aur == mein kya fark hai?
= assignment hai (variable reference banata/update karta hai). == comparison hai (equality test karta hai, boolean return karta hai).Jab aap y = x karte ho aur x ek list hai, to kya hota hai?
copy.deepcopy() use karo.ML mein while loop vs for loop kab use karein?
range(0, 100, 32) kya produce karta hai? :: [0, 32, 64, 96]. 0 se start, 32 se step, 100 se pehle stop. Batch indices ke liye useful hai.
ML mein int vs float kyun important hai? :: Float precision gradient descent mein numerical stability affect karti hai. Discrete counts ke liye Integer (epochs, batch indices). Galat mixing se shape errors ya precision loss hoti hai.
break aur continue mein kya fark hai?
break poore loop se turant bahar nikal jaata hai. continue current iteration mein baaki statements skip karta hai aur next iteration par jump karta hai.if predictions: kya check karta hai?
For loops ke mukable list comprehensions kyun use karein?
[preprocess(x) for x in dataset].[x**2 for x in range(5) if x % 2 == 0] ka output kya hai?
*args aur **kwargs mein kya fark hai?
*args positional arguments ko tuple mein capture karta hai. **kwargs keyword arguments ko dict mein capture karta hai. Flexible function APIs ke liye use hota hai.Python mein if-checks ki jagah try-except kyun use karein?
Exception handling mein finally kya karta hai?
Generators memory-efficient kyun hote hain?
List aur tuple mein kya fark hai?
Python mein float 3.7 ko int mein kaise convert karo?
int(3.7) returns 3 (zero ki taraf truncate karta hai, round nahi karta). Rounding ke liye pehle round(3.7) phir int() use karo.Python mein 5 + 2.0 ka result kya hai?
Python 3 mein dataset_size / batch_size float kyun return karta hai?
/ hamesha true division karta hai (float return karta hai). Discrete step counts ke liye // (floor division, int return karta hai) use karo.