x = 5
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:
forloops andwhileloops.
1 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:
x <- 5
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)2 For Loops
- The syntax for constructing a
forloop is as follows:
for i in range(a,b):
# body of the loop- The variable
iis 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
3 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
forloop. - Count the number of vowels in a given string.
- Given a list of numbers, print only the even numbers.
4 While Loops
- The syntax for creating a
whileloop 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 += 11
4
9
16
25
- A
forloop is best when the number of iterations is known in advance, making the code shorter and easier to read. In contrast, awhileloop is more flexible and useful when the number of iterations cannot be predetermined, such as when it depends on external conditions like user input.
5 Break and Continue
- The
breakstatement 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 += 11
2
3
for i in range(1, 6):
if i == 3:
break
print(i)1
2
The
continuestatement 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
6 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
ifstatement. Its syntax is:
if condition:
# code to execute when the condition is TrueIf-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-elsestatement.
Syntax:
if condition:
# code to execute if condition is True
else:
# code to execute if condition is Falsegrade = 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-elsestatement.
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 Truegrade = 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.
7 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–elsein a single line. - General syntax:
value_if_true if condition else value_if_falseExample 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–elseblocks for readability.
8 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
9 Exercises
3.A — Warm-ups (For loops)
- Write a
forloop 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 × 1up 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
whileloop, 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 ≥ 80Aif 75 ≤ score ≤ 79A-if 70 ≤ score ≤ 74Bif 65 ≤ score ≤ 69Fotherwise
3.G — Ternary Expressions
- Write a one-line expression that sets the variable
parityto"Even"ifnis even, otherwise to"Odd". - Write a one-line expression that sets the variable
statusto"Pass"ifgrade >= 40, otherwise to"Fail".