PYTHON FOR BEGINNERS
DAY 5 STUDY NOTES
Conditionals • Loops • Lead Priority Classifier
if / elif / else for & while loops break & continue Project: Classifier
SECTION 1 - CONDITIONALS
1. Conditionals: if / elif / else
Conditionals let your program make decisions. Based on whether a condition is True or False, Python
executes different blocks of code. This is the backbone of any smart application.
1.1 The if Statement
The simplest form - Python checks one condition:
# Syntax
if condition:
# code runs ONLY if condition is True
# Example
temperature = 35
if temperature > 30:
print("It's hot today!")
🔑 Key Rule: Indentation
Python uses 4 spaces (or 1 Tab) to define code blocks.
Everything indented under if belongs to that block.
Missing indentation = IndentationError!
1.2 The if / else Statement
When you want to handle both possibilities (True and False):
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")
# Output: You cannot vote yet.
1.3 The if / elif / else Chain
When there are multiple conditions to check, use elif (short for "else if"). Python checks each
condition in order and stops at the first True one:
score = 72
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
# Output: Grade: C
📌 How elif Works
Python checks if → then elif → then elif → finally else.
As soon as ONE condition is True, it runs that block and SKIPS the rest.
You can have as many elif blocks as you need.
else is optional - it catches everything that didn't match.
1.4 Comparison Operators (used in conditions)
Operator Meaning Example
== Equal to age == 18
!= Not equal to name != 'admin'
> Greater than salary > 50000
< Less than score < 40
>= Greater than or equal percentage >= 75
<= Less than or equal price <= 1000
1.5 Logical Operators (combining conditions)
You can combine multiple conditions using and, or, and not:
age = 25
income = 60000
has_job = True
# AND - both must be True
if age >= 18 and income >= 30000:
print("Loan eligible")
# OR - at least one must be True
if age < 18 or age > 65:
print("Special pricing applies")
# NOT - reverses True/False
if not has_job:
print("Unemployed - not eligible")
1.6 Nested Conditions
You can place an if inside another if. This is called nesting. Use it when the second condition only
makes sense if the first is already True:
is_member = True
purchase_amount = 1500
if is_member:
if purchase_amount >= 1000:
print("You get a 20% loyalty discount!")
else:
print("Spend more to unlock discount.")
else:
print("Join our membership for discounts.")
# Output: You get a 20% loyalty discount!
⚠️ Caution with Nesting
Too many nested levels make code hard to read.
Rule of thumb: avoid going deeper than 3 levels.
If nesting gets complex, consider using functions to break it apart.
1.7 Short-hand: Ternary (One-liner) Condition
# Regular if/else
x = 10
if x > 5:
label = "Big"
else:
label = "Small"
# Same thing - one line (Ternary expression)
label = "Big" if x > 5 else "Small"
print(label) # Output: Big
SECTION 2 - LOOPS
2. Loops: for, while, break, continue, range()
Loops let you repeat code automatically without writing it multiple times. Python has two types of
loops: for loops and while loops.
2.1 The for Loop
A for loop iterates over a sequence (like a list, string, or range) - it repeats once for each item:
# Looping over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
Looping over a String
# Each character is visited one by one
word = "Python"
for letter in word:
print(letter)
# Output: P y t h o n (each on new line)
2.2 The range() Function
The range() function generates a sequence of numbers. It is the most common tool used inside for
loops:
Usage Generates Example Output
range(5) 0, 1, 2, 3, 4 0 to 4
range(1, 6) 1, 2, 3, 4, 5 1 to 5
range(0, 10, 2) 0, 2, 4, 6, 8 Even numbers
range(10, 0, -1) 10, 9, 8, …, 1 Countdown
# range() examples
for i in range(5):
print(i) # 0 1 2 3 4
for i in range(1, 6):
print(i) # 1 2 3 4 5
for i in range(0, 11, 2):
print(i) # 0 2 4 6 8 10
# range(start, stop, step)
# stop value is NEVER included
2.3 The while Loop
A while loop keeps running as long as its condition remains True. You use it when you don't know in
advance how many times to repeat:
count = 1
while count <= 5:
print(f"Count is: {count}")
count += 1 # IMPORTANT: update the variable!
print('Done!')
# Output:
# Count is: 1
# Count is: 2
# Count is: 3
# Count is: 4
# Count is: 5
# Done!
🚨 Infinite Loop Warning
If the condition never becomes False, the loop runs FOREVER!
Always make sure something inside the loop changes the condition.
Example of infinite loop (DON'T do this):
while True:
print('This never stops!')
Press Ctrl+C to force stop an infinite loop in the terminal.
2.4 break - Stop the Loop Early
The break statement immediately exits the loop, even if the condition is still True or there are items
left:
# Search for a number in a list
numbers = [4, 8, 15, 16, 23, 42]
target = 16
for num in numbers:
if num == target:
print(f"Found {target}!")
break # Stop searching - we found it!
print(f"Checking {num}...")
# Output:
# Checking 4...
# Checking 8...
# Checking 15...
# Found 16!
2.5 continue - Skip to Next Iteration
The continue statement skips the rest of the current iteration and jumps to the next one. The loop
does NOT stop:
# Print only even numbers
for i in range(1, 11):
if i % 2 != 0: # If odd...
continue # ...skip it
print(i) # Only even numbers reach here
# Output: 2 4 6 8 10
break vs continue - Quick Comparison
break → Exits the loop entirely. No more iterations.
continue → Skips only this iteration. Loop continues from the next item.
Think of it like a factory conveyor belt:
continue = skip one bad item and keep the belt running
break = stop the belt completely
2.6 Nested Loops
A loop inside another loop. The inner loop completes fully for each single iteration of the outer loop:
# Multiplication table (3x3)
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
print("---")
# Output:
# 1 x 1 = 1
# 1 x 2 = 2
# 1 x 3 = 3
# ---
# 2 x 1 = 2 ... and so on
2.7 The else Clause on Loops
Python allows an else block after a loop. It runs only if the loop completed without hitting a break:
for i in range(1, 6):
if i == 10: # This will never be True
break
else:
print("Loop finished without break!")
# Output: Loop finished without break!
SECTION 3 - PROJECT: LEAD PRIORITY CLASSIFIER
3. Project: Lead Priority Classifier
This project combines conditionals and loops to build a CRM-style lead scoring system. Each lead
has a deal value (in INR) and a pipeline stage. The system classifies leads as:
Priority Label Criteria
HIGH HIGH Value ≥ 1,00,000 AND stage is 'proposal' or
'negotiation'
NURTURE NURTURE Value ≥ 25,000 OR stage is 'qualified'
DROP DROP All others (low value, cold leads)
3.1 The Lead Data
# Sample leads - each is a list: [name, deal_value, stage]
leads = [
["Arvind Sharma", 150000, "negotiation"],
["Priya Nair", 18000, "cold"],
["Kiran Patel", 75000, "proposal"],
["Meena Rajan", 30000, "qualified"],
["Suresh Kumar", 5000, "cold"],
["Deepa Iyer", 200000, "negotiation"],
["Raj Malhotra", 40000, "qualified"],
["Anjali Singh", 8000, "cold"],
]
3.2 The Classifier Logic
# Lead Priority Classifier
# ─────────────────────────────────────────
leads = [
["Arvind Sharma", 150000, "negotiation"],
["Priya Nair", 18000, "cold"],
["Kiran Patel", 75000, "proposal"],
["Meena Rajan", 30000, "qualified"],
["Suresh Kumar", 5000, "cold"],
["Deepa Iyer", 200000, "negotiation"],
["Raj Malhotra", 40000, "qualified"],
["Anjali Singh", 8000, "cold"],
]
print("=" * 55)
print(f" {"NAME":<20} {"VALUE":>10} {"STAGE":<14} PRIORITY")
print("=" * 55)
for lead in leads:
name = lead[0]
value = lead[1]
stage = lead[2]
# ── Classification Logic ──
if value >= 100000 and stage in ['proposal', 'negotiation']:
priority = "HIGH"
elif value >= 25000 or stage == 'qualified':
priority = "NURTURE"
else:
priority = "DROP"
print(f" {name:<20} {value:>10,} {stage:<14} {priority}")
print("=" * 55)
3.3 Expected Output
=======================================================
NAME VALUE STAGE PRIORITY
=======================================================
Arvind Sharma 1,50,000 negotiation HIGH
Priya Nair 18,000 cold DROP
Kiran Patel 75,000 proposal NURTURE
Meena Rajan 30,000 qualified NURTURE
Suresh Kumar 5,000 cold DROP
Deepa Iyer 2,00,000 negotiation HIGH
Raj Malhotra 40,000 qualified NURTURE
Anjali Singh 8,000 cold DROP
=======================================================
3.4 Code Breakdown - Line by Line
Code What it does
for lead in leads: Loops through each lead in the list
name = lead[0] Gets the name (index 0 of each sub-list)
value = lead[1] Gets the deal value (index 1)
stage = lead[2] Gets the pipeline stage (index 2)
stage in ['proposal', ...] Checks if stage matches any item in the list
value >= 100000 and ... Both conditions must be True for HIGH
value >= 25000 or ... Either condition True = NURTURE
f'{name:<20}' f-string: left-align name in 20 character width
f'{value:>10,}' Right-align value with comma formatting
3.5 Enhanced Version - Count by Priority
Let's extend the project to also count how many leads fall into each category:
# Enhanced: count leads by priority
high_count = 0
nurture_count = 0
drop_count = 0
for lead in leads:
name, value, stage = lead[0], lead[1], lead[2]
if value >= 100000 and stage in ['proposal', 'negotiation']:
priority = "HIGH"
high_count += 1
elif value >= 25000 or stage == 'qualified':
priority = "NURTURE"
nurture_count += 1
else:
priority = "DROP"
drop_count += 1
print(f"{name}: {priority}")
# Summary
print("\n--- SUMMARY ---")
print(f"HIGH: {high_count} leads")
print(f"NURTURE: {nurture_count} leads")
print(f"DROP: {drop_count} leads")
SECTION 4 - QUICK REFERENCE & PRACTICE
4. Quick Reference Cheat Sheet
4.1 Conditionals Summary
# if only
if condition:
# runs if True
# if / else
if condition:
# runs if True
else:
# runs if False
# if / elif / else
if condition1:
# first match
elif condition2:
# second match
elif condition3:
# third match
else:
# nothing matched
# Nested
if outer:
if inner:
# both are True
# Ternary
result = "Yes" if condition else "No"
4.2 Loops Summary
# for loop - iterate over sequence
for item in sequence:
# use item
# for with range
for i in range(start, stop, step):
# use i
# while loop
while condition:
# repeat until False
# always update condition!
# break - exit loop
for item in sequence:
if some_condition:
break
# continue - skip iteration
for item in sequence:
if skip_condition:
continue
# this runs for non-skipped items
4.3 Common Mistakes to Avoid
Mistake Fix
❌ Using = instead of == in condition == is comparison; = is assignment
❌ Forgetting to indent after if/for/while Always use 4 spaces consistently
❌ Infinite while loop (condition never False) Update the loop variable inside the loop
❌ Off-by-one with range() range(5) gives 0-4, not 1-5
❌ Confusing break and continue break stops loop; continue skips one step
4.4 Practice Exercises
Exercise 1 - Grade Calculator
Write a program that:
1. Takes a list of 5 student scores
2. Loops through each score
3. Prints: PASS if score >= 40, FAIL otherwise
4. Also counts and prints total PASS and FAIL at the end
Exercise 2 - FizzBuzz
Loop through numbers 1 to 30:
• Print 'Fizz' if divisible by 3
• Print 'Buzz' if divisible by 5
• Print 'FizzBuzz' if divisible by both 3 AND 5
• Otherwise print the number
Hint: Use % (modulo) to check divisibility
Exercise 3 - Extend the Lead Classifier
Add these features to today's project:
1. Add a 'skip' for leads with value = 0 (use continue)
2. Stop processing if a lead named 'STOP' appears (use break)
3. Calculate and print the total value of HIGH leads only