Chapter 4 - Control Flow (Python)
Chapter 4 - Control Flow (Python)
SCIENTIFIC
SKEE1033
CONTROL FLOW
( WEEK 4 )
SKEE1033 2
OPERATION (RECAP)
STATEMENT FUNCTION
TYPE
Execute statements specified Boolean
number of times using
while COMMAND
BOOLEAN OPERATOR
or ITERATION PROTOCOL for
Direct instructions
often used in the
syntax command line
3. DECISION
Execute statements if if REPL: Read-Eval-Print Loop, which
condition is TRUE using if-else is an interactive programming
if-elif-else environment that takes single user
BOOLEAN OPERATOR
inputs (commands), evaluates them,
and returns the result to the user.
SKEE 1033
3
INTRODUCTION
Conditional
1) Decision statement.
2) Enables the computer to choose and execute one of several sets of
statements based on a given condition
SKEE1033 4
PYTHON SCRIPT
SKEE1033 5
CREATE & RUN A SCRIPT
Clicking the New Script icon will open a new script editor.
Write the code inside the editor and save it as .py file.
Then run the code by either typing the file name on the command
window or click the Run icon on the IDE window.
SKEE1033 6
CONDITIONAL
CONDITIONAL
if-elif-else
EXECUTE STATEMENTS IF
CONDITION IS TRUE
if condition_1:
statements
elif condition_2:
statements
else:
statements
SKEE1033 8
if-elif-else STATEMENT
non-neg
SKEE1033 9
if-else STATEMENT
true
SKEE1033 10
MULTIPLE CONDITIONS WITH if-else
Example 3: Check whether the discriminant d is zero and if a is non-
zero. If both conditions are satisfied, it calculates x; otherwise, it
returns 'Different root'. For the quadratic equation:
𝒂𝒂𝒙𝒙𝟐𝟐 + 𝒃𝒃𝒃𝒃 + 𝒄𝒄 = 𝟎𝟎
the equation has equal roots, given by −𝒃𝒃/(𝟐𝟐𝟐𝟐) provided that
𝒃𝒃𝟐𝟐 − 𝟒𝟒𝟒𝟒𝟒𝟒 = 𝟎𝟎 and 𝒂𝒂 ≠ 𝟎𝟎.
# Input values for a, b, and c This code use logical operator && to set
a = float(input('Input a value: ')) a multiple conditions for when to
b = float(input('Input b value: '))
compute the equal roots x.
c = float(input('Input c value: '))
SKEE1033 11
MULTIPLE CONDITIONS WITH if-elif-else
Example 4: Determine the value of d and find the roots based on whether d
is zero, positive, or negative. Calculate the roots accordingly, considering all
conditions with a≠0.
If d > 0 there are two real solutions.
If d = 0 there is one real solution.
If d < 0 the solutions are complex
# Input values for a, b, and c This code use elif since
a = float(input('Input a value: ‘)) there are more than 2
b = float(input('Input b value: ‘))
conditions.
c = float(input('Input c value: ‘))
SKEE1033 12
NESTED if
Example 5: Calculate the discriminant and uses nested if statements to
determine the roots. It first checks if a is non-zero; if true, it evaluates the
discriminant: equal roots when zero, distinct roots when positive, and
complex roots otherwise. If a is zero, it calculates a single root.
# Input values for a, b, and c When a=0, the quadratic
a = float(input('Input a value: ‘)) equation becomes linear
b = float(input('Input b value: ‘))
equation. Thus, only one root
c = float(input('Input c value: ‘))
# Calculate the discriminant available and computed as x1 in
d = b**2 - 4 * a * c the outer else.
# Nested if statements
if a != 0:
if d == 0:
x1 = -b / (2 * a) x2 = x1
print(f'The roots are both: {x1}’)
elif d > 0:
x1 = (-b + (d**0.5)) / (2 * a)
x2 = (-b - (d**0.5)) / (2 * a)
print(f'The roots are: {x1} and {x2}’)
else:
print('Complex root’) Input a value: 2
else: Input b value: 3
x1 = -c / b Input c value: 1
print(f'The root is: {x1}') The roots are: -0.5 and -1.0
SKEE1033 13
DECISION USING LOGICAL
SKEE1033 14
DECISION USING LOGICAL
Example 6: A simplified method of calculating income tax can be
illustrated using the table below.
SKEE1033 15
DECISION USING LOGICAL
Example 6: Below is how the tax payable calculation is solve using
if-elif-else
# Input the taxable income
inc = float(input('Input an income: ‘))
SKEE1033 16
DECISION USING LOGICAL
…
var_n = formula_n * condition_n
var = var_1 + var_2 + ... + var_n
How it work:
Only one condition will evaluate to True at a time. Therefore, the addition
in the final line will produce the output of the formula corresponding to the
True condition.
SKEE1033 17
DECISION USING LOGICAL
SKEE1033 18
LOOP CONTROL
LOOP CONTROL
SYNTAX
(a>0)or(b==10) for index in range(start, stop, step):
FOR Statements;
DETERMINATE
LOOPS
INDETERMINATE
LOOPS
Repeat *Or value is not 0
while when arithmetic
condition is expression is used
true (not recommended).
SKEE1033 20
for LOOP
Example 8: Compound Interest Calculation using for Loop
Let’s consider a formula of compound interest as below where 𝑎𝑎 is the
invested money, 𝑟𝑟 = interest rate, 𝑛𝑛 = total year, and 𝐵𝐵 = final balance:
𝑛𝑛
𝐵𝐵 = 𝑎𝑎 1 + 𝑟𝑟
If 𝐵𝐵 is to be evaluated for 𝑎𝑎 = $100 on 5 different total year 𝑛𝑛 (2,4,6,8,10) and
interest rate of 𝑟𝑟 = 8%, below is how the for loop is use to compute all of the
𝐵𝐵 values.
SKEE1033 21
while LOOP
Example 9: Compound Interest Calculation using while Loop
Below is how the same equation is coded with while loop:
# Define the initial investment and interest rate
a = 100 # Initial investment amount in dollars
r = 0.08 # Annual interest rate
# Use a while loop to calculate for each specified year (2, 4, 6, 8, 10)
while n <= 10:
B = a * (1 + r) ** n # Calculate the final balance
print(f'n = {n}, B = {B:.2f}') # Display the year and the calculated balance
n += 2 # Increment the year by 2
n = 2, B = 116.64
n = 4, B = 136.05
n = 6, B = 158.69
n = 8, B = 185.09
n = 10, B = 215.89
SKEE1033 22
RETURNING VECTORS AS OUTPUT
Example 10: Monitoring Capacitor Charge over Time using a while
Loop
When a resistor (R), capacitor (C) and battery (V) are connected in series, a
charge Q builds up on the capacitor according to the formula:
𝑡𝑡
−
𝑄𝑄 𝑡𝑡 = 𝐶𝐶𝐶𝐶 1 − 𝑒𝑒 𝑅𝑅𝑅𝑅
where t is the charging time starts at 0. The problem is to monitor the charge
on the capacitor every 0.5 second in order to detect when it reaches a level of
2 units of charge, given that V=9, R=4 and C=1.
Write a program which display the time and charge every 0.5 seconds until
the charge first exceeds 2 units (i.e. the last charge displayed must exceed 2).
Next slide shows how the problem is coded with while loop:
SKEE1033 23
RETURNING VECTORS AS OUTPUT
Example 10a (using append):
import math # Import math for calculations
SKEE1033 24
RETURNING VECTORS AS OUTPUT
Example 10b (using +=):
import math # Import math for calculations
# Use a while loop to calculate charge and time until charge exceeds 2
while q <= 2:
q = C * V * (1 - [Link](-t / (R * C))) # Calculate charge
Q += [round(q, 4)] # Add the rounded charge value to Q
T += [t] # Add the time value to T
t += time_increment # Increment time
SKEE1033 25
NESTED LOOP
Example 11: Compound Interest with Nested Loops for Multiple
Principal and Time Periods
Lets again consider a formula of compound interest. Now, B is to be evaluated
for 3 values of a ($100,$500,$800) on 5 different total year of n
(2,4,6,8,10). This time, let r=0.09.
Since now we also need to compute for several values of a, we need two loop
statements.
# Values for the principal amounts
a_values = [100, 500, 800]
# Interest rate
r = 0.09
SKEE1033 26
NESTED LOOP
Example 11 (continued):
for a in a_values: # Loop through each value of a
for n in n_values: # Loop through each value of n
B = a * (1 + r) ** n # Calculate the final balance using the compound formula
print(f"For a = {a}, n = {n}, B = {B:.2f}") # Print the results
SKEE1033 27
continue STATEMENT
SKEE1033 28
break STATEMENT
Example 13
Let’s write a simple random number guessing game where you need to
continuously guess a random number until your guess is correct.
In Python, the random number can be generated using the randint()
function from the random module. In this example, to generate a random
number between 1 and 6, we use the function [Link](1,6).
Observe that the endless loop is terminated using the break statement
once the correct guess is made.
SKEE1033 29
break STATEMENT
Example 13: Random Number Guessing Game using a while Loop
and break Statement
import random # Import the random module to generate random numbers
SKEE1033 30
VECTORIZING FOR LOOP
Example 14: Vectorization of Compound Interest Calculation in
Python with Matrix Form Output
Given Python’s design, using loops, especially nested ones, can
sometimes be less efficient in terms of computing time.
Let’s revisit Example 11, where the compound interest B is calculated for
three principal amounts ($100,$500,$800) over five different years
(n=2,4,6,8,10 ) with an interest rate of r=0.09.
By vectorizing the principal amounts using Python, we can eliminate
one of the loops, efficiently computing all the B values.
In the resulting matrix, each row corresponds to a different principal
amount, and each column corresponds to a different year, effectively
representing the results in a table format of a versus n.
SKEE1033 31
VECTORIZING FOR LOOP
Example 14: Vectorization of Compound Interest Calculation in
Python with Matrix Form Output
# Import NumPy for array operations
import numpy as np
SKEE1033 32
VECTORIZING FOR LOOP
Example 14: Understanding enumerate() and idx:
1. enumerate() Function:
o built-in Python function that adds a counter (index) to an iterable, such
as a list or a range.
o Generates pairs of (index, value) for each item in the iterable, where:
index starts at 0 by default and increments by 1 with each iteration.
Iteration Breakdown:
First Iteration (idx = 0, n = 2):
Calculation: a * (1 + r) ** n
For a = 100: 100 * (1 + 0.09) ** 2 = 118.81
For a = 500: 500 * (1 + 0.09) ** 2 = 594.05
For a = 800: 800 * (1 + 0.09) ** 2 = 950.48
Updated Matrix B:
Store these values in the first column (idx = 0):
B =
[[118.81 0. 0. 0. 0. ]
[594.05 0. 0. 0. 0. ]
[950.48 0. 0. 0. 0. ]]
SKEE1033 34
VECTORIZING FOR LOOP
Example 14: Iteration breakdown, walk through each interation in
details and show how the matrix B is filled with values
Second Iteration (idx = 1, n = 4):
Calculation: a * (1 + r) ** n
For a = 100: 100 * (1 + 0.09) ** 4 = 138.59
For a = 500: 500 * (1 + 0.09) ** 4 = 692.96
For a = 800: 800 * (1 + 0.09) ** 4 = 1108.74
Updated Matrix B:
Store these values in the second column (idx = 1):
B =
[[118.81 138.59 0. 0. 0. ]
[594.05 692.96 0. 0. 0. ]
[950.48 1108.74 0. 0. 0. ]]
SKEE1033 35
VECTORIZING FOR LOOP
Example 14: Iteration breakdown, walk through each interation in
details and show how the matrix B is filled with values
Third Iteration (idx = 2, n = 6):
Calculation: a * (1 + r) ** n
For a = 100: 100 * (1 + 0.09) ** 6 = 161.22
For a = 500: 500 * (1 + 0.09) ** 6 = 806.09
For a = 800: 800 * (1 + 0.09) ** 6 = 1289.74
Updated Matrix B:
Store these values in the third column (idx = 2):
B =
[[118.81 138.59 161.22 0. 0. ]
[594.05 692.96 806.09 0. 0. ]
[950.48 1108.74 1289.74 0. 0. ]]
SKEE1033 36
VECTORIZING FOR LOOP
Example 14: Iteration breakdown, walk through each interation in
details and show how the matrix B is filled with values
Fourth Iteration (idx = 3, n = 8):
Calculation: a * (1 + r) ** n
For a = 100: 100 * (1 + 0.09) ** 8 = 187.87
For a = 500: 500 * (1 + 0.09) ** 8 = 939.34
For a = 800: 800 * (1 + 0.09) ** 8 = 1502.94
Updated Matrix B:
Store these values in the fourth column (idx = 3):
B =
[[118.81 138.59 161.22 187.87 0. ]
[594.05 692.96 806.09 939.34 0. ]
[950.48 1108.74 1289.74 1502.94 0. ]]
SKEE1033 37
VECTORIZING FOR LOOP
Example 14: Iteration breakdown, walk through each interation in
details and show how the matrix B is filled with values
Fifth Iteration (idx = 4, n = 10):
Calculation: a * (1 + r) ** n
For a = 100: 100 * (1 + 0.09) ** 10 = 218.71
For a = 500: 500 * (1 + 0.09) ** 10 = 1093.57
For a = 800: 800 * (1 + 0.09) ** 10 = 1749.71
Updated Matrix B:
Store these values in the fifth column (idx = 4):
B =
[[118.81 138.59 161.22 187.87 218.71]
[594.05 692.96 806.09 939.34 1093.57]
[950.48 1108.74 1289.74 1502.94 1749.71]]
SKEE1033 38
REPLACE LOOPS WITH ARRAY OPERATIONS
Example 15: Vectorization to Remove Loops
for loops are useful, but in scientific programming, using arrays and
vectorized operations can make calculations faster and more efficient
by avoiding the use of loops
Based on Example 11, the remaining for loop can be removed by
further extending vectorization techniques.
Using Python's [Link] function, vectors a and n are expanded
into two-dimensional arrays A and N. These arrays are then directly used
in calculations to produce the 2D array B
SKEE1033 39
REPLACE LOOPS WITH ARRAY OPERATIONS
Example 15: Vectorization to Remove Loops
import numpy as np # Import NumPy for array operations
Resulting Array B:
[[ 118.81 141.158161 167.71001108 199.25626417 236.73636746]
[ 594.05 705.790805 838.55005542 996.28132085 1183.6818373 ]
[ 950.48 1129.265288 1341.68008867 1594.05011335 1893.89093967]]
SKEE1033 40
LOOP STATEMENT VS ARRAY OPERATION
Example 16: Performance Comparison: Vectorized Array Operations
vs. Nested Loops
import numpy as np
import time
# Measure time for array operation using meshgrid and element-wise operations
start_time = [Link]()
N, A = [Link](n, a)
B = A * (1 + r) ** N
time1 = [Link]() - start_time
SKEE1033 41
LOOP STATEMENT VS ARRAY OPERATION
Example 16 (continued):
SKEE1033 42
AVOIDING LOOP & DECISION STATEMENTS
Example 17: Tax calculation script that avoids loops and decision
statements
Returning to Example 6, we will create a program to calculate the tax for
various income values, such as [4000 12000 18000 23000 30000],
while avoiding the use of loops and conditional statements.
Key Concepts Used:
Vectorized Operations: Calculations are done directly on arrays, making
them efficient and concise.
Boolean Indexing: Conditions are applied directly on arrays without using
explicit if statements, allowing selective calculations.
Avoidance of Loops and Decision Statements: The entire tax calculation
is achieved without any loops (for or while) or if conditions, making the
code much more readable and faster.
SKEE1033 43
AVOIDING LOOP & DECISION STATEMENTS
Example 17: Tax calculation script that avoids loops and decision
statements
import numpy as np # Import NumPy for array operations
# Sum the tax components to get the total tax for each income
tax = tax1 + tax2 + tax3
SKEE1033 44
CONTROL FLOW DRILL
SKEE1033 45