Day 4: Conditions, Loops & Functions
✅ 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
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 checks conditions top to bottom
- 2The first True condition runs; the rest are skipped
- 3
elseruns only if nothing above was True - 4Indentation (4 spaces) shows which lines belong to which 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: repeat for every 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 and 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
A comprehension builds a new list in one readable line: [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: write once, use everywhere
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))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
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 unlocked today
Practice tasks
🏋️ Practice – do it yourself
bill(units) and test 80, 150 and 320 units.Show 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] make a list of numbers above the average using a comprehension.Show 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])
Show solution
amount, years = 50000, 0
while amount < 100000:
amount *= 1.07
years += 1
print(years, "years ->", round(amount))Quick quiz
🧠 Quick Quiz – test yourself
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.
Day 5: store data in lists, tuples, dictionaries and sets – the building blocks behind every DataFrame.
