Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🐍 Week 1 – Python for Data Science  ·  Day 04

Day 4: Conditions, Loops & Functions

⏱ 2 hours📶 Beginner🎯 100% self-study
Day 4 / 60

✅ Today you will learn

  • if / elif / else for business rules
  • for and while loops over data
  • break, continue, enumerate, zip and range
  • List comprehensions – one-line loops
  • Functions, default arguments, return values and lambda

🏢 In the real world

A bank gives every customer a risk band – Low, Medium or High – from income and credit score. Ten lakh customers, one rule: the rule is an if-elif-else, the ten lakh is a loop, and wrapping it in a function lets the whole team reuse it.

Decisions with 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 checks conditions top to bottom
  2. 2The first True condition runs; the rest are skipped
  3. 3else runs only if nothing above was True
  4. 4Indentation (4 spaces) shows which lines belong to which block
How if-elif-else is evaluated
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: repeat for every 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 and 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

A comprehension builds a new list in one readable line: [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: write once, use everywhere

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
💡 Function habits of good analysts

One job per function, a clear name (verb + noun), a docstring, and return the result instead of printing it – then you can test it and reuse it in pandas with .apply() (Day 17).

Real example: grade report for a class

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 unlocked today

✔ Turn business rules into if-elif-else✔ Loop over records with enumerate and zip✔ Write list comprehensions✔ Build reusable functions

Practice tasks

🏋️ Practice – do it yourself

Task 1: Electricity bill: first 100 units ₹5, next 100 units ₹7, above 200 units ₹9. Write bill(units) and test 80, 150 and 320 units.
Show 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: From [23, 45, 12, 67, 34, 89, 21] make a list of numbers above the average using a comprehension.
Show 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: A savings account earns 7% per year. Using a while loop, find how many years ₹50,000 takes to double.
Show 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 – test yourself

1. Which block runs if no condition is True?
else is the fallback branch.
2. What does continue do inside a loop?
continue skips the rest of the current iteration.
3. [x*2 for x in range(3)] gives…
range(3) is 0, 1, 2; doubled gives 0, 2, 4.
4. What does a function return if it has no return statement?
Python returns None by default.
5. zip(["a","b"], [1,2]) pairs items…
zip joins the 1st with the 1st, 2nd with the 2nd and so on.

Interview corner

💼 Interview Corner

What is the difference between print and return in a function?

print only shows a value on the screen; return sends the value back to the caller so it can be stored, tested or used in more calculations. Data code should return.

When would you use a lambda?

For a tiny throw-away function used once, typically as a key for sorted(), or inside pandas apply/map. For anything longer or reused, write a normal def with a name and docstring.

Summary

  • if/elif/else picks the first True branch.
  • for loops walk through data; enumerate and zip make them cleaner.
  • Comprehensions: [expr for x in data if cond].
  • Functions with defaults and return make logic reusable.
➡️ Next

Day 5: store data in lists, tuples, dictionaries and sets – the building blocks behind every DataFrame.

Frequently Asked Questions

Why does Python use indentation instead of braces?
It forces readable code. Use 4 spaces per level and never mix tabs and spaces.
Are loops slow for big data?
Plain Python loops are slow for millions of rows. From Day 8 you will use NumPy and pandas, which do the same work 10–100× faster without explicit loops.
What is a docstring?
The text in triple quotes right under def. It explains what the function does and appears in help() and Shift+Tab in Jupyter.
← Data Science (60 Days)
🔗

Share this topic with a friend

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

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

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

Next topicDay 5: Lists, Tuples, Dictionaries & Sets Your progress: 4 / 60 (7%) · Lesson 5 / 60 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free