दिन 4: Conditions, Loops और Functions
✅ आज आप सीखेंगे
- Business rules के लिए if / elif / else
- Data पर for और while loops
- break, continue, enumerate, zip और range
- List comprehensions – एक line के loops
- Functions, default arguments, return values और lambda
🏢 असली दुनिया में
Bank हर customer को income और credit score से risk band देता है – Low, Medium या High। दस लाख customers, एक नियम: नियम if-elif-else है, दस लाख loop है, और इसे function में रखने से पूरी team इसे दोबारा इस्तेमाल कर सकती है।
if / elif / else से फ़ैसले
credit_score = 712
if credit_score >= 750:
band = "Low risk"
elif credit_score >= 650:
band = "Medium risk"
else:
band = "High risk"
print(credit_score, "->", band)- 1Python conditions ऊपर से नीचे जाँचता है
- 2पहली True condition चलती है; बाकी छूट जाती हैं
- 3
elseतभी चलता है जब ऊपर कुछ True न हो - 4Indentation (4 spaces) बताता है कौन सी line किस block की है
amount, is_member = 2400, True
shipping = 0 if amount >= 499 else 40 # one-line if
discount = 0.10 if is_member and amount > 2000 else 0
print("Shipping:", shipping, "| Discount:", discount)for loops: हर record के लिए दोहराएँ
orders = [1499, 299, 15999, 649, 2499]
total = 0
for amount in orders:
total += amount
print("Total:", total, "| Orders:", len(orders), "| Average:", total / len(orders))cities = ["Delhi", "Mumbai", "Pune"]
sales = [125000, 98000, 64000]
for i, city in enumerate(cities, start=1):
print(i, city)
for city, amt in zip(cities, sales):
print(f"{city:8} ₹{amt:,}")
for month in range(1, 13, 3):
print("Quarter starts in month", month)break, continue और while
temps = [31, 33, 36, 41, 39, 44, 29]
for day, t in enumerate(temps, 1):
if t < 35:
continue # skip normal days
if t >= 44:
print("Day", day, ": heat-wave alert! stop checking")
break
print("Day", day, ": hot", t)balance, emi, month = 120000, 15500, 0 # loan payoff
while balance > 0:
balance -= emi
month += 1
print("Loan finished in", month, "months; extra paid:", -balance)List comprehensions
Comprehension एक readable line में नई list बनाता है: [expression for item in data if condition]।
prices = [499, 1299, 2499, 89, 15999] with_gst = [round(p * 1.18) for p in prices] premium = [p for p in prices if p > 1000] labels = ["High" if p > 2000 else "Low" for p in prices] print(with_gst) print(premium) print(labels)
Functions: एक बार लिखें, हर जगह इस्तेमाल करें
def risk_band(score, income):
"""Return the risk band of a loan applicant."""
if score >= 750 and income >= 50000:
return "Low"
elif score >= 650:
return "Medium"
return "High"
applicants = [(780, 85000), (700, 30000), (610, 90000)]
for s, inc in applicants:
print(s, inc, "->", risk_band(s, inc))def final_price(price, discount=0.0, gst=0.18):
"""Price after discount, then GST."""
return round(price * (1 - discount) * (1 + gst), 2)
print(final_price(1000)) # default discount and gst
print(final_price(1000, discount=0.2))
print(final_price(1000, 0.1, gst=0.05))def summary(numbers):
"""Return several statistics at once (a tuple)."""
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, avg = summary([42, 77, 58, 91, 66])
print(f"min {low}, max {high}, avg {avg:.1f}")
square = lambda x: x * x # tiny one-line function
print(sorted(["Pune", "Agra", "Delhi"], key=lambda c: len(c)))
print(square(12))हर function का एक काम, साफ़ नाम (verb + noun), docstring, और result print करने की जगह return करें – तब आप उसे test कर सकते हैं और pandas में .apply() से दोबारा इस्तेमाल कर सकते हैं (Day 17)।
असली example: class की grade report
def grade(avg):
if avg >= 90: return "A1"
if avg >= 80: return "A2"
if avg >= 70: return "B1"
if avg >= 60: return "B2"
if avg >= 33: return "C"
return "Fail"
students = {"Aman": [88, 92, 79], "Priya": [95, 97, 91], "Rahul": [45, 30, 52], "Sneha": [72, 68, 75]}
counts = {}
for name, marks in students.items():
avg = sum(marks) / len(marks)
g = grade(avg)
counts[g] = counts.get(g, 0) + 1
print(f"{name:6} avg {avg:5.1f} grade {g}")
print("Grade count:", counts)🏅 आज के Job Skills
Practice tasks
🏋️ Practice – ख़ुद करें
bill(units) लिखें और 80, 150 और 320 units test करें।Solution देखें
def bill(units):
if units <= 100:
return units * 5
if units <= 200:
return 100 * 5 + (units - 100) * 7
return 100 * 5 + 100 * 7 + (units - 200) * 9
for u in [80, 150, 320]:
print(u, "units ->", bill(u))[23, 45, 12, 67, 34, 89, 21] से comprehension द्वारा average से बड़े numbers की list बनाएँ।Solution देखें
nums = [23, 45, 12, 67, 34, 89, 21] avg = sum(nums) / len(nums) print(round(avg, 2), [n for n in nums if n > avg])
Solution देखें
amount, years = 50000, 0
while amount < 100000:
amount *= 1.07
years += 1
print(years, "years ->", round(amount))Quick quiz
🧠 Quick Quiz – ख़ुद को जाँचें
Interview corner
💼 Interview Corner
Function में print और return में क्या फ़र्क है?
print सिर्फ़ screen पर value दिखाता है; return value को caller को वापस भेजता है ताकि उसे store, test या आगे की गणना में इस्तेमाल किया जा सके। Data code में return करें।
Lambda कब इस्तेमाल करेंगे?
छोटे, एक बार के function के लिए, जैसे sorted() की key या pandas apply/map के अंदर। लंबा या दोबारा इस्तेमाल होने वाला हो तो नाम और docstring वाला normal def लिखें।
सारांश
- if/elif/else पहली True branch चुनता है।
- for loops data पर चलते हैं; enumerate और zip उन्हें साफ़ बनाते हैं।
- Comprehensions: [expr for x in data if cond]।
- Defaults और return वाले functions logic को reusable बनाते हैं।
Day 5: data को lists, tuples, dictionaries और sets में रखना – हर DataFrame की नींव।
