3 Control Flow

Important Note on Python Syntax

  • Indentation, not braces
    • Unlike R, Python does not use {} braces to structure code blocks.
    • Instead, Python relies on indentation (whitespace at the beginning of a line).
  • Colons (:)
    • A colon at the end of a statement (if, for, while, def, etc.) indicates the start of a new block.
    • The code that follows must be indented consistently.
  • You may use spaces or tabs, but be consistent within a file.
  • The convention is 4 spaces per indentation level.
  • Incorrect indentation will raise an IndentationError.

Example: if in R vs Python

R:

x <- 5
if (x > 0) {
  print("Positive")
} else {
  print("Non-positive")
}

Python:

x = 5
if x > 0:
    print("Positive")
else:
    print("Non-positive")

Example: for loop in R vs Python

R:

for (i in 1:5) {
  print(i^2)
}

Python:

for i in range(1, 6):
    print(i**2)

For Loops

  • The syntax for constructing a for loop is as follows:
for i in range(a,b): 
    # body of the loop
  • The variable i is referred to as a loop counter

Looping over Lists

names_list = ['Alex', 'Beth', 'Chad', 'Drew', 'Emma']

for name in names_list:
    print(f'Hello, {name}!')
Hello, Alex!
Hello, Beth!
Hello, Chad!
Hello, Drew!
Hello, Emma!

Looping over Ranges

for i in range(0,5):
    print('The value of i is', i)
The value of i is 0
The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
  • Example: A python function to calculate the sum of the squares of the first 100 integers
# Sum the first 100 positive integers
total = 0
for i in range(1,101):
    total += i**2

print(total)
338350

Other Iterables

  • A for loop can work with any iterable object.
  • An iterable is anything that can return its elements one at a time (for example, in a loop).
  • Common iterables in Python:
    • Lists[1, 2, 3]
    • Tuples(4, 5, 6)
    • Strings"hello"
    • Rangesrange(5)
    • Sets{1, 2, 3}
    • Dictionaries{"a": 1, "b": 2} (iterates over keys by default)
for char in "isrt, du":
    print(char)
i
s
r
t
,
 
d
u
for key in {"x": 1, "y": 2}:
    print(key)
x
y

Exercise 3.1

Write a python function to:

  • calculate the sum of squares of elements in a list.
  • Print the multiplication table of 7 using a for loop.
  • Count the number of vowels in a given string.
  • Given a list of numbers, print only the even numbers.

While Loops

  • The syntax for creating a while loop is as follows:
while condition:
    # code to be executed each iteration
  • Example: Print out the squares of the first five positive integers.
n = 1
while n <= 5:
    print(n**2)
    n += 1
1
4
9
16
25
  • A for loop is best when the number of iterations is known in advance, making the code shorter and easier to read. In contrast, a while loop is more flexible and useful when the number of iterations cannot be predetermined, such as when it depends on external conditions like user input.

Break and Continue

  • The break statement immediately exits the loop when a condition is met.
    • Useful when you want to stop once a desired value is found.
i = 1
while i < 6:
    print(i)
    if i == 3:
        break
    i += 1
1
2
3
for i in range(1, 6):
    if i == 3:
        break
    print(i)
1
2

  • The continue statement skips the current iteration and moves to the next cycle of the loop.

    • Useful to skip specific values during iteration without stopping the loop.
i = 1
while i < 6:
    i += 1
    if i == 3:
        continue
    print(i)
2
4
5
6
for i in range(1, 6):
    if i == 3:
        continue
    print(i)
1
2
4
5

Conditional Statements

  • Conditional statements allow us to control whether or how certain parts of our code will execute, based on logical conditions we specify.

  • The most basic form is the if statement. Its syntax is:

if condition:
    # code to execute when the condition is True

If-Else Statements

  • Sometimes, we need to choose between two alternatives: one block if the condition is true, and another if it is false.
  • This is achieved using an if-else statement.

Syntax:

if condition:
    # code to execute if condition is True
else:
    # code to execute if condition is False
grade = 42

if grade >= 40:
    print("You passed the exam.")
    print("Congratulations!")
else:
    print("You failed the exam.")
    print("Better luck next time.")
You passed the exam.
Congratulations!

If-Elif-Else Statements

  • Sometimes, we need to choose from more than two alternatives.
  • In such cases, we use an if-elif-else statement.

Syntax:

if condition1:
    # code to execute if condition1 is True
elif condition2:
    # code to execute if condition1 is False, but condition2 is True
elif condition3:
    # code to execute if all above are False, but condition3 is True
elif condition4:
    # code to execute if all above are False, but condition4 is True
...

else:
    # code to execute if none of the above conditions are True
grade = 75

if grade >= 80:
    print("You got an 'A+' on the exam.")
elif grade >= 75:
    print("You got a 'A' on the exam.")
elif grade >= 70:
    print("You got a 'A-' on the exam.")
elif grade >= 65:
    print("You got a 'B' on the exam.")
else:
    print("You got an 'F' on the exam.")
You got a 'A' on the exam.

Ternary (Conditional) Expressions

  • Now that we understand full if-else blocks, Python also provides a shorthand form called ternary expressions.
  • A ternary expression is a shorthand way to write an if–else in a single line.
  • General syntax:
value_if_true if condition else value_if_false

Example 1:

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

Example 2:

x = -5
sign = "Positive" if x > 0 else "Zero" if x == 0 else "Negative"
print(sign)
Negative

We can break it into multiple lines for readability:

sign = (
    "Positive" if x > 0
    else "Zero" if x == 0
    else "Negative"
)
  • Use ternary expressions for simple decisions.
  • For more complex logic, use regular if–else blocks for readability.

Summary

  • For loop → predetermined number of iterations
  • While loop → runs until condition is False
  • Break → exit loop, Continue → skip iteration
  • If-Else → choose between two paths
  • If-Elif-Else → choose between multiple paths
  • Ternary expression → compact one-line if–else for simple cases

Exercises

3.A — Warm-ups (For loops)

  1. Write a for loop that prints the squares of all integers from 1 to 10 (inclusive).
  2. Given the list nums = [3, 10, -4, 7, 0, 9], use a loop to print only the positive numbers.
  3. Write a program that asks for a string and counts how many of its characters are vowels (a, e, i, o, u), ignoring case.

3.B — Ranges & Aggregation

  1. Use a loop to compute the sum of the cubes of integers from 1 to 50.
  2. Compute the product of all integers from 1 to 8 (that is, calculate 8!).
  3. Print the multiplication table for 6, showing results from 6 × 1 up to 6 × 10.

3.C — Looping over Iterables

  1. Loop over the string "ISRT, DU" and print each character, skipping commas and spaces.
  2. Given the dictionary d = {"x": 4, "y": 9, "z": 16}, print each key along with the square root of its value.

3.D — While Loops

  1. Using a while loop, print the first 7 powers of 2: 1, 2, 4, 8, ....
  2. Write a program that processes numbers in a list one by one. Stop when a negative number is found, and print the sum of all the numbers before that negative number.

3.E — Break & Continue

  1. Given nums = [5, 12, 7, 0, 13, 9], use a loop to print each number until you reach 0. At that point, stop the loop immediately (use break).
  2. Write a loop that prints all numbers from 1 to 20, but skips the multiples of 3 (use continue).

3.F — If / Elif / Else

Write a program that reads a student’s percentage score (an integer between 0 and 100) and prints their letter grade according to the following rules:

  • A+ if score ≥ 80
  • A if 75 ≤ score ≤ 79
  • A- if 70 ≤ score ≤ 74
  • B if 65 ≤ score ≤ 69
  • F otherwise

3.G — Ternary Expressions

  1. Write a one-line expression that sets the variable parity to "Even" if n is even, otherwise to "Odd".
  2. Write a one-line expression that sets the variable status to "Pass" if grade >= 40, otherwise to "Fail".