= 5
x if x > 0:
print("Positive")
else:
print("Non-positive")
3 Control Flow
- A loop is a tool that allows us to instruct Python to repeat a task several times, usually with slight variations each time.
- We will consider two types of loops in this course:
for
loops andwhile
loops.
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).
- Unlike R, Python does not use
- 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.
- A colon at the end of a statement (
- 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:
<- 5
x if (x > 0) {
print("Positive")
else {
} print("Non-positive")
}
Python:
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
= ['Alex', 'Beth', 'Chad', 'Drew', 'Emma']
names_list
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
= 0
total for i in range(1,101):
+= i**2
total
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"
- Ranges →
range(5)
- Sets →
{1, 2, 3}
- Dictionaries →
{"a": 1, "b": 2}
(iterates over keys by default)
- Lists →
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.
= 1
n while n <= 5:
print(n**2)
+= 1 n
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, awhile
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.
= 1
i while i < 6:
print(i)
if i == 3:
break
+= 1 i
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.
= 1
i while i < 6:
+= 1
i 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
= 42
grade
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
= 75
grade
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:
if condition else value_if_false value_if_true
Example 1:
= 20
age = "Adult" if age >= 18 else "Minor"
status print(status)
Adult
Example 2:
= -5
x = "Positive" if x > 0 else "Zero" if x == 0 else "Negative"
sign 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)
- Write a
for
loop that prints the squares of all integers from 1 to 10 (inclusive). - Given the list
nums = [3, 10, -4, 7, 0, 9]
, use a loop to print only the positive numbers. - 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
- Use a loop to compute the sum of the cubes of integers from 1 to 50.
- Compute the product of all integers from 1 to 8 (that is, calculate 8!).
- Print the multiplication table for 6, showing results from
6 × 1
up to6 × 10
.
3.C — Looping over Iterables
- Loop over the string
"ISRT, DU"
and print each character, skipping commas and spaces. - 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
- Using a
while
loop, print the first 7 powers of 2:1, 2, 4, 8, ...
. - 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
- Given
nums = [5, 12, 7, 0, 13, 9]
, use a loop to print each number until you reach0
. At that point, stop the loop immediately (usebreak
). - 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 ≥ 80A
if 75 ≤ score ≤ 79A-
if 70 ≤ score ≤ 74B
if 65 ≤ score ≤ 69F
otherwise
3.G — Ternary Expressions
- Write a one-line expression that sets the variable
parity
to"Even"
ifn
is even, otherwise to"Odd"
. - Write a one-line expression that sets the variable
status
to"Pass"
ifgrade >= 40
, otherwise to"Fail"
.