1οΈβ£ Variables
β Quick explanation
A variable is a name that stores a value in memory so you can reuse it.
β Real-life analogy
Think of a tiffin box with a label:
- Label = variable name
- Food inside = value
You can change the food anytime; the label stays.
β Syntax
x = 10
name = "Ali"
price = 99.5
is_active = True
β Real-life ML example
When training a model:
learning_rate = 0.001
epochs = 20
batch_size = 32
β Important note
Python decides the data type automatically.
2οΈβ£ Loops
Loops help you repeat tasks without writing repeated code.
πΉ for loop
Used when you know how many times to repeat.
Example
fruits = ["apple", "banana", "mango"]
for f in fruits:
print(f)
Output:
apple
banana
mango
Real-life analogy
You check every message in WhatsApp one by one β a loop.
ML example
Looping through data batches:
for batch in data_loader:
train(batch)
πΉ while loop
Used when you donβt know how many times but want to repeat until a condition becomes false.
Example
count = 1
while count <= 5:
print(count)
count += 1
Real-life analogy
You keep scrolling Instagram until your battery is dead.
"Bhai jab tak battery > 0, loop chalta rahega."
3οΈβ£ Functions
Functions are reusable blocks of code.
β Why functions?
- Avoid repeating code
- Keep logic clean & modular
- Essential for ML pipeline (data cleaning, model training, evaluation)
β Syntax
def greet(name):
return "Hello " + name
Using it:
print(greet("Ali"))
Real-life example
You cook maggi in a fixed process:
- Boil water
- Add masala
- Add noodles
- Serve
This whole process is a function.
ML example
def train_model(model, data, epochs):
for epoch in range(epochs):
model.train(data)
π₯ Putting it all together
def square_numbers(nums):
result = [] # variable (list)
for n in nums: # for loop
result.append(n*n)
return result # function output
numbers = [2, 3, 5]
print(square_numbers(numbers))
Output:
[4, 9, 25]
β Common Mistakes
- Missing indentation (Python is strict).
- Forgetting
:after loops & function definitions. - Wrong variable names like
1var(names cannot start with a number). - Infinite while loops (
while True:without break).
π§ Mini Quiz
Try to answer mentally.
Q1
What will this print?
x = 5
while x < 8:
print(x)
x = x + 1
Q2
Write a function that returns the cube of a number.
Q3
What type of loop would you use to train a model until loss < 0.01?
Top comments (0)