3 Control Flow

(CSE331) Python for Data Science

Author
Affiliation

Md Rasel Biswas

IASDS, University of Dhaka

Control flow determines which statements run and how often they run. We begin with decisions, then use loops to process collections.

1 Blocks and Indentation

  • A colon (:) starts a block after statements such as if, for, while, and def.
  • Indent the statements in a block by four spaces. Use spaces consistently; do not mix tabs and spaces.
  • Statements at the same indentation level belong to the same block.
  • Indentation can change the meaning of valid code as well as cause syntax errors.

Unlike R, Python does not use braces to delimit these blocks.

# R
x <- 5
if (x > 0) {
  print("Positive")
}
# Python
x = 5
if x > 0:
    print("Positive")
print("Finished checking")  # outside the block
Positive
Finished checking

2 Conditional Statements

2.1 If and else

An if block runs when its condition is true. An optional else block handles the other case.

score = 42
if score >= 40:
    print("You passed the exam.")
else:
    print("You failed the exam.")
You passed the exam.

Use == for an equality comparison. = is assignment.

2.2 Multiple branches: elif

Python checks conditions from top to bottom and runs the first matching branch.

score = 75
if score < 0 or score > 100:
    print("Invalid score")
elif score >= 80:
    print("Excellent")
elif score >= 60:
    print("Good")
elif score >= 40:
    print("Pass")
else:
    print("Fail")
Good

These labels are illustrative performance categories, not the University’s letter-grade scale. Put higher cutoffs first when testing score >= cutoff.

2.3 Missing values and short-circuiting

and stops as soon as an operand is false; or stops as soon as an operand is true. This can avoid an invalid operation.

score = None
if score is not None and score >= 40:
    print("Pass")
else:
    print("Missing score or below the pass mark")
Missing score or below the pass mark

The comparison score >= 40 is not evaluated when score is None.

Do not use if score: to identify a recorded score: a legitimate score of 0 is also false.

2.4 Conditional expressions

Use a conditional expression to select a value in a short, simple decision:

age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Adult

Syntax: value_if_true if condition else value_if_false. For several branches, an ordinary if/elif/else block is usually clearer.

3 For Loops

A for loop takes each item from an iterable. Lists, tuples, strings, ranges, dictionaries, and sets are iterable.

names = ["Ayesha", "Imran", "Nadia"]
for name in names:
    print(f"Hello, {name}!")
Hello, Ayesha!
Hello, Imran!
Hello, Nadia!

The loop variable holds the current item. It need not be a numerical counter.

3.1 Repetition using range

range(start, stop, step) excludes stop.

for i in range(1, 6):
    print(i, i**2)
1 1
2 4
3 9
4 16
5 25

3.2 Accumulating a result

Initialize the total before the loop.

# Sum of squares of the first 100 positive integers
total = 0
for i in range(1, 101):
    total += i**2
print(total)
338350

Use a built-in function when it already expresses the calculation:

values = [4, 7, 2]
print(sum(values))
13

3.3 Filtering into a new list

values = [5, -2, 0, 8, -1]
positive_values = []
for value in values:
    if value > 0:
        positive_values.append(value)
print(positive_values)
[5, 8]

Create a new collection when filtering. Removing items from the list you are currently iterating over can skip items unexpectedly.

4 Looping over Dictionaries

Looping directly over a dictionary gives its keys. Use .items() to obtain keys and values together.

scores = {"Ayesha": 72, "Imran": 64, "Nadia": 81}
for name, score in scores.items():
    print(name, score)
Ayesha 72
Imran 64
Nadia 81

Here each key-value pair is unpacked into two variables.

5 While Loops

A while loop repeats as long as its condition remains true.

n = 1
while n <= 5:
    print(n**2)
    n += 1
1
4
9
16
25

Use for when processing an iterable; use while when repetition is controlled by a condition. A for loop does not require knowing the number of items in advance.

# How many doublings are needed to reach at least 100?
value = 3
doublings = 0
while value < 100:
    value *= 2
    doublings += 1
print(value, doublings)
192 6

Ensure the condition can eventually become false, or provide a reachable break. Interrupt the kernel if a loop runs indefinitely.

6 Break and Continue

6.1 break: stop the loop

values = [5, 12, 7, 0, 13, 9]
for value in values:
    if value == 0:
        break
    print(value)
5
12
7

break exits the innermost enclosing loop, not the entire program.

6.2 continue: skip the remaining loop body

for n in range(1, 7):
    if n == 3:
        continue
    print(n)
1
2
4
5
6

In a while loop, take care not to skip the update that allows the loop to finish:

n = 0
while n < 6:
    n += 1
    if n == 3:
        continue
    print(n)
1
2
4
5
6

Both examples print 1, 2, 4, 5, and 6.

7 Nested Loops

The inner loop runs for each item in the outer loop.

for row in range(1, 4):
    for column in range(1, 4):
        print(row, column, row * column)
1 1 1
1 2 2
1 3 3
2 1 2
2 2 4
2 3 6
3 1 3
3 2 6
3 3 9

To process a list of lists:

rows = [[4, 7], [2, 9], [5, 6]]
total = 0
for row in rows:
    for value in row:
        total += value
print(total)
33

8 Worked Example: Recorded Scores

We will use None for a missing score. A score of zero must remain in the calculation.

students = [
    {"name": "Ayesha", "score": 72},
    {"name": "Imran", "score": None},
    {"name": "Nadia", "score": 0},
    {"name": "Rafi", "score": 84},
]

total = 0
count = 0
for student in students:
    score = student["score"]
    if score is None:
        continue
    total += score
    count += 1

if count > 0:
    print(f"Mean of {count} recorded scores: {total / count:.2f}")
else:
    print("No recorded scores")
Mean of 3 recorded scores: 52.00

Expected mean: 52.00, using three recorded scores.

9 Exercises

Use loops and conditions; user-defined functions are introduced next.

9.1 Conditions

  1. Classify a number as positive, negative, or zero.
  2. Given a score, check whether it lies in 0 to 100. For a valid score, print Pass if it is at least 40 and Fail otherwise.
  3. Write a conditional expression assigning "Even" or "Odd" to parity for an integer n.

9.2 For loops and aggregation

  1. Print the multiplication table of 7, from 7 × 1 to 7 × 10.
  2. Compute the product of the integers from 1 to 8 using a loop.
  3. Count the vowels in text = "Applied Statistics", ignoring case.
  4. For nums = [3, 10, -4, 7, 0, 9], build a new list containing only positive values.
  5. Given d = {"x": 4, "y": 9, "z": 16}, print each key and the square root of its value.

9.3 While, break, and continue

  1. Starting from 1, repeatedly double a value until it exceeds 1,000. Print the final value and number of doublings.
  2. Sum the numbers in [4, 7, 2, -1, 9] until the first negative value appears. Exclude that negative value and all later values.
  3. Print integers from 1 to 20, skipping multiples of 3 with continue.

9.4 Combined practice

  1. Find the sum of each row in [[3, 5], [2, 8], [4, 6]] using nested loops.
  2. For the student records above, count missing scores and count recorded scores of at least 40. Check that a recorded zero is handled correctly.

10 Summary

  • Conditions select which code runs; their order matters.
  • for processes an iterable; while repeats according to a condition.
  • Initialize accumulators outside the loop.
  • Use .items() to loop over dictionary keys and values together.
  • Distinguish missing values from zero and handle empty results explicitly.

11 Further reading