Skip to main content
Python for Data Science
CHAPTER 05 Beginner

Conditional Statements and Loops

Updated: May 18, 2026
5 min read

# CHAPTER 5

Conditional Statements and Loops

1. Chapter Introduction

Programs are useless if they can only run in a straight line. Data science requires logic: *If* a customer is VIP, *then* apply a discount. Furthermore, you don't want to write the same line of code 10,000 times to process 10,000 rows of data. This chapter covers Control Flow—using conditional if statements to make decisions, and for loops to automate repetitive tasks.

2. Conditional Statements (if, elif, else)

The if statement evaluates a condition (using the comparison operators from Chapter 4). If the condition evaluates to True, the indented block of code runs.

python
12345
age = 22

# Simple IF
if age >= 18:
    print("You are an adult.")

For more complex logic, we add elif (Else If) and else.

python
12345678910
score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

*How it works:* Python evaluates from top to bottom. The moment it finds a True condition, it executes that block and skips the rest.

3. The for Loop

A for loop iterates over a sequence (like a list, string, or a range of numbers) and executes a block of code for each item. This is how you automate repetitive data processing.

1. Looping over a List:

python
1234
fruits = ["Apple", "Banana", "Cherry"]

for item in fruits:
    print(f"I like {item}s")

2. Looping over a Range of Numbers: The range(start, stop) function generates a sequence of numbers. (Note: It stops *before* the stop number).

python
123
# Prints 0, 1, 2, 3, 4
for i in range(5):
    print(i)

4. The while Loop

A while loop continues to execute *as long as* a specific condition remains True.

python
12345
count = 0

while count < 3:
    print(f"Count is {count}")
    count += 1  # Equivalent to: count = count + 1

*Warning:* If you forget to update the condition (like forgetting count += 1), the loop will run forever (an Infinite Loop) and crash your program!

5. Loop Control: break and continue

Sometimes you need to interrupt a loop before it finishes naturally.

break: Stops the entire loop immediately.

python
1234567
# Find the first even number and stop
numbers = [1, 3, 5, 8, 9]

for num in numbers:
    if num % 2 == 0:
        print(f"Found even number: {num}")
        break  # Loop terminates here

continue: Skips the rest of the *current* iteration and moves to the next item.

python
12345
# Print only odd numbers
for i in range(5):
    if i % 2 == 0:
        continue # Skip the print statement below for even numbers
    print(i)

6. Mini Project: Student Grade Calculator

Let's build a program that processes a list of student scores, calculates their letter grade, and counts how many students passed.

python
12345678910111213141516171819202122232425
scores = [95, 42, 78, 88, 55, 91]
passed_count = 0

for score in scores:
    # 1. Determine Grade
    if score >= 90:
        grade = "A"
    elif score >= 80:
        grade = "B"
    elif score >= 70:
        grade = "C"
    else:
        grade = "F"
        
    # 2. Count passes
    if score >= 70:
        passed_count += 1
        status = "Passed"
    else:
        status = "Failed"
        
    print(f"Score: {score} | Grade: {grade} | Status: {status}")

print("-" * 20)
print(f"Total students passed: {passed_count} out of {len(scores)}")

7. Common Mistakes

  • Forgetting the colon : Every if, elif, else, for, and while statement MUST end with a colon.
  • Indentation Errors: The code inside the loop or if-statement MUST be indented. Code that is not indented is considered outside the loop.
  • Infinite While Loops: Creating a while True: loop without a break statement inside it will freeze your computer.

8. MCQs

Question 1

What keyword is used to check multiple alternative conditions in Python?

Question 2

In a Python for loop, what determines which code belongs inside the loop?

Question 3

What does range(3) generate?

Question 4

Which loop runs indefinitely as long as a condition remains true?

Question 5

What does the break statement do?

Question 6

What does the continue statement do?

Question 7

Every if and for statement line must end with which character?

Question 8

If x = 10, which block will execute? if x > 5: print("A"); elif x > 8: print("B")?

Question 9

How do you increment a counter variable by 1?

Question 10

What happens if a while loop condition never evaluates to False?

9. Interview Questions

  • Q: Explain the difference between break and continue in a loop. Give a data-cleaning scenario where you would use each.
  • Q: Why is the order of if / elif statements important? What happens if you check if score > 50 before checking if score > 90?

11. Summary

Control flow makes code intelligent. if/elif/else blocks allow the program to make decisions based on changing data. for loops are essential for iterating through datasets or lists of files, while while loops execute until a condition changes. Use break to exit loops early, and continue to skip specific items (like skipping invalid rows in a dataset).

12. Next Chapter Recommendation

In Chapter 6: Functions and Modules in Python, we will learn how to wrap our logic and loops into reusable, named blocks of code, and how to import external libraries.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·