Python Loops(While & For)
Python has two primitive loop commands:
Why loops matter in AI/ML
Loops are used everywhere in:
- Training models (epochs, iterations)
- Data preprocessing
- Feature engineering
- Optimization algorithms
- Batch processing
forLoop
for item in iterable:
# do somethingLoop through dataset
data = [10, 20, 30, 40]
for value in data:
print(value)Training loop (Epochs)
epochs = 5
for epoch in range(epochs):
print(f"Training epoch {epoch}")When weuse: Neural network training
Batch Processing in ML
data = list(range(100))
batch_size = 10
for i in range(0, len(data), batch_size):
batch = data[i:i+batch_size]
print(batch)When we use
- Deep learning (mini-batch gradient descent)
Scaling
data = [100, 200, 300]
scaled = []
for x in data:
scaled.append(x / 100)
print(scaled)Loop with
enumerate()(Index + Value)
features = ['age', 'salary', 'experience']
for i, feature in enumerate(features):
print(i, feature)When we use
- Feature mapping
- Model input indexing
Nested Loops (Matrix operations)
matrix = [[1, 2], [3, 4]]
for row in matrix:
for val in row:
print(val)When we use
- Image processing
- Tensor operations
Dictionary Loop in ML configs
params = {'lr': 0.01, 'epochs': 10}
for key, value in params.items():
print(key, value)
whileLoop (Condition-Based)
while condition:
# run until condition is Falsewhile loop
i = 0
while i < 5:
print(i)
i += 1Training until convergence
loss = 10
while loss > 0.1:
print("Training... Loss:", loss)
loss *= 0.5When we use:
- Stop training when loss is low
Get Jagadeesh Karri’s stories in your inbox
Join Medium for free to get updates from this writer.
Data streaming (Real-time AI)
import random
while True:
data = random.randint(1, 100)
print("Incoming data:", data)
if data > 90:
breakWhen We use
- Real-time ML systems
- Sensor data processing
Retry mechanism
attempts = 0
while attempts < 3:
print("Trying model API...")
success = False
if success:
break
attempts += 1When we use
- API calls (OpenAI, ML services)
- Fault tolerance
Loop Control Statements
break (Stop loop)
for i in range(10):
if i == 5:
break
print(i)continue (Skip iteration)
for i in range(5):
if i == 2:
continue
print(i)pass (Do nothing placeholder)
for i in range(5):
passAdvanced Patterns for AI/ML
Simulating Gradient Descent
weight = 10
learning_rate = 0.1
for _ in range(10):
gradient = 2 * weight
weight = weight - learning_rate * gradient
print(weight)Data Filtering
data = [10, -5, 20, -2]
cleaned = [x for x in data if x > 0]
print(cleaned)Loop + NumPy ML usage
import numpy as np
arr = np.array([1, 2, 3])
for val in arr:
print(val * 2)Early Stopping ML concept
losses = [0.9, 0.7, 0.6, 0.6, 0.6]
for i in range(1, len(losses)):
if losses[i] == losses[i-1]:
print("Early stopping triggered")
break
forvswhile(When to use)
ScenarioUseKnown iterations (epochs, batches)forUnknown iterations (until condition)whileDataset traversalforConvergence / streamingwhile
AI/ML Workflow Example
epochs = 3
data = [1, 2, 3, 4]
for epoch in range(epochs):
print(f"Epoch {epoch}")
for x in data:
prediction = x * 2
print("Prediction:", prediction)Important for ML Concepts
- Prefer
forloops → cleaner & safer - Use
whilefor: - convergence
- streaming data
- Avoid heavy loops → use:
- NumPy
- Pandas
- Vectorization (faster 🚀)
Interview Questions
- Difference between
forandwhile? - How to implement early stopping?
- How to process batches in ML?
- Why avoid loops in NumPy?




