Pichhle lesson me humne data store karna seekha. Ab seekhenge ki us data pe baar-baar kaam kaise karein — loops aur functions se.
for loop
Example
daily_sales = [1200, 850, 430, 2100]
total = 0
for amount in daily_sales:
total = total + amount
print("Total sales:", total)
Output
Total sales: 4580
enumerate() se value ke saath uska index bhi milta hai, aur zip() se do lists ek saath chalti hain:
Example
days = ["Mon", "Tue", "Wed", "Thu"]
for i, amount in enumerate(daily_sales, start=1):
print(i, amount)
for day, amount in zip(days, daily_sales):
print(f"{day}: Rs {amount}")
Output
1 1200
2 850
3 430
4 2100
Mon: Rs 1200
Tue: Rs 850
Wed: Rs 430
Thu: Rs 2100
Functions — code ko reuse karna
Jo kaam baar-baar karna ho, uska function bana lijiye. def se function banta hai aur return se result wapas aata hai:
Example
def percentage_change(old, new):
return round((new - old) / old * 100, 2)
print(percentage_change(200, 250))
print(percentage_change(500, 450))
Output
25.0
-10.0
Parameter ki default value bhi de sakte hain:
Example
def apply_discount(price, discount=10):
return price - price * discount / 100
print(apply_discount(1000)) # default 10% discount
print(apply_discount(1000, 25)) # 25% discount
Output
900.0
750.0
lambda — chhota, ek line ka function
lambda ek bina naam ka chhota function hai. Iska sabse common use sorting me key dena hai. Pandas me bhi apply(lambda ...) bahut dikhega:
Example
products = [("Pen", 20), ("Bag", 850), ("Book", 300)]
by_price = sorted(products, key=lambda item: item[1])
print(by_price)
Output
[('Pen', 20), ('Book', 300), ('Bag', 850)]
List comprehension — loop ek line me
Nayi list banane ka Pythonic tareeka. Syntax: [expression for item in list if condition]
Example
prices = [100, 250, 80, 400]
with_gst = [round(p * 1.18, 2) for p in prices]
expensive = [p for p in prices if p > 150]
print(with_gst)
print(expensive)
Output
[118.0, 295.0, 94.4, 472.0]
[250, 400]
Isi tarah dictionary comprehension bhi hoti hai:
Example
cities = ["Delhi", "Mumbai", "Pune"]
name_length = {city: len(city) for city in cities}
print(name_length)
Output
{'Delhi': 5, 'Mumbai': 6, 'Pune': 4}
try / except — errors ko handle karna
Real data me galat values aati hi hain. try/except se program crash nahi hota — galat value skip ho jaati hai:
Example
raw_values = ["120", "95", "abc", "", "300"]
clean = []
for value in raw_values:
try:
clean.append(int(value))
except ValueError:
print(f"Skip kiya: {value!r}")
print(clean)
Output
Skip kiya: 'abc'
Skip kiya: ''
[120, 95, 300]
Data Science me aap loops kam aur vectorized operations (NumPy/Pandas) zyada use karenge, kyunki wo kai guna fast hote hain. Par loops aur functions ki samajh har jagah kaam aati hai.
Practice
- Ek function
bmi(weight, height)banaiye jo BMI return kare (weight / height²). - List comprehension se 1 se 20 tak ke saare even numbers ke square nikaaliye.
["10", "x", "30"]me se sirf valid numbers ka total nikaaliye.