Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🐍 Week 1 – Data Science के लिए Python  ·  दिन 04

दिन 4: Conditions, Loops और Functions

⏱ 2 hours📶 Beginner🎯 100% self-study
दिन 4 / 60

✅ आज आप सीखेंगे

  • 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 से फ़ैसले

Python
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)
712 -> Medium risk
  1. 1Python conditions ऊपर से नीचे जाँचता है
  2. 2पहली True condition चलती है; बाकी छूट जाती हैं
  3. 3else तभी चलता है जब ऊपर कुछ True न हो
  4. 4Indentation (4 spaces) बताता है कौन सी line किस block की है
if-elif-else कैसे जाँचा जाता है
Python
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)
Shipping: 0 | Discount: 0.1

for loops: हर record के लिए दोहराएँ

Python
orders = [1499, 299, 15999, 649, 2499]
total = 0
for amount in orders:
    total += amount
print("Total:", total, "| Orders:", len(orders), "| Average:", total / len(orders))
Total: 20945 | Orders: 5 | Average: 4189.0
Python
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)
1 Delhi 2 Mumbai 3 Pune Delhi ₹125,000 Mumbai ₹98,000 Pune ₹64,000 Quarter starts in month 1 Quarter starts in month 4 Quarter starts in month 7 Quarter starts in month 10

break, continue और while

Python
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)
Day 3 : hot 36 Day 4 : hot 41 Day 5 : hot 39 Day 6 : heat-wave alert! stop checking
Python
balance, emi, month = 120000, 15500, 0     # loan payoff
while balance > 0:
    balance -= emi
    month += 1
print("Loan finished in", month, "months; extra paid:", -balance)
Loan finished in 8 months; extra paid: 4000

List comprehensions

Comprehension एक readable line में नई list बनाता है: [expression for item in data if condition]।

Python
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)
[589, 1533, 2949, 105, 18879] [1299, 2499, 15999] ['Low', 'Low', 'High', 'Low', 'High']

Functions: एक बार लिखें, हर जगह इस्तेमाल करें

Python
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))
780 85000 -> Low 700 30000 -> Medium 610 90000 -> High
Python
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))
1180.0 944.0 945.0
Python
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))
min 42, max 91, avg 66.8 ['Pune', 'Agra', 'Delhi'] 144
💡 अच्छे analysts की function आदतें

हर function का एक काम, साफ़ नाम (verb + noun), docstring, और result print करने की जगह return करें – तब आप उसे test कर सकते हैं और pandas में .apply() से दोबारा इस्तेमाल कर सकते हैं (Day 17)।

असली example: class की grade report

Python
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)
Aman avg 86.3 grade A2 Priya avg 94.3 grade A1 Rahul avg 42.3 grade C Sneha avg 71.7 grade B1 Grade count: {'A2': 1, 'A1': 1, 'C': 1, 'B1': 1}

🏅 आज के Job Skills

✔ Business rules को if-elif-else में बदलना✔ enumerate और zip के साथ records पर loop✔ List comprehensions लिखना✔ Reusable functions बनाना

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: बिजली bill: पहली 100 units ₹5, अगली 100 units ₹7, 200 से ऊपर ₹9। bill(units) लिखें और 80, 150 और 320 units test करें।
Solution देखें
Python
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))
80 units -> 400 150 units -> 850 320 units -> 2280
Task 2: [23, 45, 12, 67, 34, 89, 21] से comprehension द्वारा average से बड़े numbers की list बनाएँ।
Solution देखें
Python
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])
41.57 [45, 67, 89]
Task 3: Savings account 7% प्रति वर्ष देता है। while loop से पता करें ₹50,000 को दोगुना होने में कितने साल लगेंगे।
Solution देखें
Python
amount, years = 50000, 0
while amount < 100000:
    amount *= 1.07
    years += 1
print(years, "years ->", round(amount))
11 years -> 105243

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. कोई condition True न हो तो कौन सा block चलता है?
else fallback branch है।
2. Loop में continue क्या करता है?
continue मौजूदा iteration का बाकी हिस्सा छोड़ देता है।
3. [x*2 for x in range(3)] क्या देता है?
range(3) = 0, 1, 2; दोगुना = 0, 2, 4।
4. Return statement के बिना function क्या लौटाता है?
Python default में None लौटाता है।
5. zip(["a","b"], [1,2]) items को कैसे जोड़ता है?
zip पहले को पहले से, दूसरे को दूसरे से जोड़ता है।

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 की नींव।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

Python braces की जगह indentation क्यों?
इससे code पढ़ने लायक रहता है। हर level पर 4 spaces रखें और tabs-spaces न मिलाएँ।
क्या बड़े data पर loops धीमे हैं?
लाखों rows पर साधारण Python loops धीमे हैं। Day 8 से आप NumPy और pandas इस्तेमाल करेंगे, जो बिना loop के 10–100 गुना तेज़ काम करते हैं।
Docstring क्या है?
def के ठीक नीचे triple quotes वाला text। यह बताता है function क्या करता है और help() तथा Jupyter में Shift+Tab पर दिखता है।
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 5: Lists, Tuples, Dictionaries और Sets आपकी प्रगति: 4 / 60 (7%) · Lesson 5 / 60 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें