0% found this document useful (0 votes)
2 views45 pages

Chapter 4 - Control Flow (Python)

Uploaded by

yy526zx813
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views45 pages

Chapter 4 - Control Flow (Python)

Uploaded by

yy526zx813
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROGRAMMING

SCIENTIFIC
SKEE1033
CONTROL FLOW
( WEEK 4 )

DR. AHMAD SHAHIDAN ABDULLAH


DR. AHMAD SHARMI ABDULLAH
DR. AMIRJAN NAWABJAN
DR. MOHD ADIB SARIJARI
DR. MUHAMMAD AL FARABI MUHAMMAD IQBAL
DR. MUHAMMAD ARIFF BAHARUDIN
PM. IR. TS. DR. ASRUL IZAM AZMI
PM. IR. TS. DR. MICHAEL TAN LOONG PENG
OBJECTIVES

1) To write a decision algorithm in Python using if and elif statements.


2) To understand the differences between if/elif statements and
determine their appropriate use cases.
3) To implement loop algorithms in Python using for and while
statements.
4) To recognize the differences between for and while loops and
determine the best situation for each.

SKEE1033 2
OPERATION (RECAP)

STATEMENT FUNCTION

1. ASSIGNMENT Group of statement


syntax
that perform a task
Assign array to a variable using syntax
EQUAL OPERATOR def function_name(input1, input2):
variable = expression # Code block
return output
2. REPITITION Arithmetic

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

 Two types of control flow:


 Loop Control
1) Repetition statement.
2) Instructs the computer to repeat a specific set of statements a defined
number of times using a for loop or while a condition is met using a while
loop.
3) Other than the above, repetition control such as skip and early exit from the
repetition are also possible.

 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

 Python scripts are the most straightforward type of program file.


 They do not accept input or output arguments.
 Scripts are ideal for automating a sequence of commands, such as
performing repeated calculations or executing a series of commands
efficiently.
 In this chapter, all examples will be presented as Python scripts, as we
require a set of commands to demonstrate control flow effectively.

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

o Condition is normally express


as Boolean expression, which
evaluate to True or False
o When using arithmetic
expressions, any non-zero
value is considered True,
while zero is considered
False.

SKEE1033 8
if-elif-else STATEMENT

 Example 1: This code checks if x is less than zero. If true, it prints


'neg'; otherwise, it prints 'non-neg'.
x = 2 This code will display ‘non-
neg’ at the command window.
if x < 0: Try change the value as x=-2
print('neg')
elif x == 0:
print('zero')
else:
print('non-neg')

non-neg

SKEE1033 9
if-else STATEMENT

 Example 2: The if condition checks for a non-zero integer (79) and


prints 'true' because it evaluates to true. If it were zero, it would print
'false'.
if 79: This code will display ‘true’ at the
print('true') command window. Try other values,
else: including zero & negative values.
print('false')

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: '))

# Calculate the discriminant


d = b**2 - 4 * a * c

# Check for specific conditions


if d == 0 and a != 0:
x = -b / (2 * a) Input a value: 20
print(f'The value of x is: {x}') Input b value: 20
else: Input c value: 30
print('Different root') Different root

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: ‘))

# Calculate the discriminant


d = b**2 - 4 * a * c

# Check for conditions using if-elif-else


if d == 0 and a != 0:
x1 = -b / (2 * a) x2 = x1
print(f'The roots are both: {x1}’)
elif d > 0 and a != 0:
x1 = (-b + (d**0.5)) / (2 * a)
x2 = (-b - (d**0.5)) / (2 * a) Input a value: 1
print(f'The roots are: {x1} and {x2}’) Input b value: 2
else: Input c value: 1
print('Complex root') The roots are both: -1.0

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

 Instead of using if statements, a logical approach can be an alternative


for executing decision-making tasks.
 This method is particularly useful in scientific programming, where
mathematical equations are frequently involved.
 Advantage:
 Logical approaches are often faster than traditional if statements.
 Can be more readable, as expressions closely resemble the mathematical
equations they represent.

 In the logical approach, conditions typically handled by if statements are


replaced with logical multipliers, allowing for concise and efficient
calculations.

SKEE1033 14
DECISION USING LOGICAL
 Example 6: A simplified method of calculating income tax can be
illustrated using the table below.

Taxable Income Tax Payable


$10000 or less 10% of taxable income
Between $10000 and $1000 + 20% of amount by which
$20000 taxable income exceeds $10,000
More than $20000 $3000 + 50% of amount by which
taxable income exceeds $20,000

The tax payable on a taxable income of $30000, for example, is:


Tax = 3000 + 0.5*(30000-20000) = 8000

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: ‘))

# Calculate the tax payable based on the income range


if inc <= 10000:
tax = 0.1 * inc
elif inc <= 20000:
tax = 1000 + 0.2 * (inc - 10000)
else:
tax = 3000 + 0.5 * (inc - 20000)

# Display the tax payable with two decimal points


print('Tax Payable =', format(tax, '.2f'))

Input an income: 30000


Tax Payable = 8000.00

SKEE1033 16
DECISION USING LOGICAL

 To convert the elif method to a logical approach, conditions are


multiplied by their respective formulas. The results of these
multiplications are then summed to obtain the final result. B
 Below is the code structure:
var_1 = formula_1 * condition_1
var_2 = formula_2 * condition_2


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

 Example 7: Below is the mathematical equation of the tax payable


calculation, followed by the python code using the logical vector
method.
0.1𝑖𝑖𝑖𝑖𝑖𝑖 𝑓𝑓𝑓𝑓𝑓𝑓 𝑖𝑖𝑖𝑖𝑖𝑖 ≤ 10000
𝑡𝑡𝑡𝑡𝑡𝑡 = � 1000 + 0.2 𝑖𝑖𝑖𝑖𝑖𝑖 − 10000 𝑓𝑓𝑓𝑓𝑓𝑓 10000 < 𝑖𝑖𝑖𝑖𝑖𝑖 ≤ 20000
3000 + 0.5 𝑖𝑖𝑖𝑖𝑖𝑖 − 20000 𝑓𝑓𝑓𝑓𝑓𝑓 𝑖𝑖𝑖𝑖𝑖𝑖 > 20000

# Input the taxable income


inc = float(input('Input an income: ‘))

# Calculate the tax payable using logical conditions


tax1 = (0.1 * inc) * (inc <= 10000)
tax2 = (1000 + 0.2 * (inc - 10000)) * (inc > 10000 and inc <= 20000)
tax3 = (3000 + 0.5 * (inc - 20000)) * (inc > 20000)

# Sum the taxes based on conditions


tax = tax1 + tax2 + tax3

# Display the tax payable


print('Tax Payable =', format(tax, '.2f'))
Input an income: 30000
Tax Payable = 8000.00

SKEE1033 18
LOOP CONTROL
LOOP CONTROL

Repeat for every


Boolean expression

a>0 index value


a<=100
(a<100)and(a>10)

SYNTAX
(a>0)or(b==10) for index in range(start, stop, step):
FOR Statements;
DETERMINATE
LOOPS

while condition range(j,k) from j to k-1


SYNTAX

Statements; WHILE range(j,k,m) from j to k-1 with step m

INDETERMINATE
LOOPS
Repeat *Or value is not 0
while when arithmetic
condition is expression is used
true (not recommended).

CONTINUE PASS CONTROL


TO NEXT
ITERATION
TERMINATE BREAK
LOOPS
EXECUTION

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.

# Define the initial investment and interest rate


a = 100 # Initial investment amount in dollars
r = 0.08 # Annual interest rate

# Loop over the specified years (2, 4, 6, 8, 10)


for n in range(2, 11, 2):
B = a * (1 + r) ** n # Calculate the final balance using the formula
print(f'n = {n}, B = {B:.2f}') # Display the year and the calculated balance
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 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

# Initialize the starting year and the step


n = 2

# 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

V=9; R=4; C=1 # Set V, R, and C values


t=0; q=0 # Initialize time and charge
Q=[]; T=[] # Lists for charge and time

# Loop until charge exceeds 2 units


while q <= 2:
q = C*V*(1 - [Link](-t/(R*C))) # Calculate charge
[Link](q); [Link](t) # Store charge and time
t += 0.5 # Increment time

# Display the charge and time, rounding charge to 4 decimal places


print("Q:", [round(val, 4) for val in Q])
print("T:", T)

Q: [0.0, 1.0575, 1.9908, 2.8144]


T: [0, 0.5, 1.0, 1.5]

SKEE1033 24
RETURNING VECTORS AS OUTPUT
 Example 10b (using +=):
import math # Import math for calculations

V=9; R=4; C=1 # Set V, R, and C values


t=0; q=0 # Initialize time and charge
Q=[]; T=[] # Lists for charge and time
time_increment = 0.5

# 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

# Display the charge and time lists


print("Q:", Q) print("T:", T)

Q: [0.0, 1.0575, 1.9908, 2.8144]


T: [0, 0.5, 1.0, 1.5]

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]

# Values for the number of years


n_values = [2, 4, 6, 8, 10]

# 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

For a = 100, n = 2, B = 118.81


For a = 100, n = 4, B = 141.16
For a = 100, n = 6, B = 167.71
For a = 100, n = 8, B = 199.26
For a = 100, n = 10, B = 236.74
For a = 500, n = 2, B = 594.05
For a = 500, n = 4, B = 705.79
For a = 500, n = 6, B = 838.55
For a = 500, n = 8, B = 996.28
For a = 500, n = 10, B = 1183.68
For a = 800, n = 2, B = 950.48
For a = 800, n = 4, B = 1129.27
For a = 800, n = 6, B = 1341.68
For a = 800, n = 8, B = 1594.05
For a = 800, n = 10, B = 1893.89

SKEE1033 27
continue STATEMENT

 continue passes control to the next iteration and skips remaining


statements. In nested loops, continue skips remaining statements only in
the body of the loop in which it occurs.
 Example 12
# Loop through numbers from 1 to 50
for n in range(1, 51): # Check if n is not divisible by 7
if n % 7 != 0:
continue # Skip the rest of the loop if n is not divisible by 7

# Print the number if it is divisible by 7 The program skip displaying n


print(f"Divisible by 7: {n}") when it is not divisible by seven.
The % symbol in Python is the
Divisible by 7: 7
modulus operator, also known as
Divisible by 7: 14
Divisible by 7: 21 the remainder operator.
Divisible by 7: 28
Divisible by 7: 35
Divisible by 7: 42
Divisible by 7: 49

SKEE1033 28
break STATEMENT

 break terminates the execution of a for or while loop. Statements in


the loop after the break statement do not execute.
 In nested loops, break exits only from the loop in which it occurs.
Control passes to the statement that follows the end of that loop.

 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

# Generate a random number between 1 and 6


x = [Link](1, 6)
n = 0 # Initialize the number of attempts

# Infinite loop to prompt the user for guesses


while True:
guess = int(input('Guess the number: ')) # Ask the user to guess the number
n += 1 # Increment the attempt count

# Check if the guessed number is correct


if guess == x:
print(f'You got it right after {n} try{"s" if n > 1 else ""}!’)
break # Exit the loop when the correct guess is made

Guess the number: 2


Guess the number: 4
Guess the number: 5
Guess the number: 6
Guess the number: 1
You got it right after 5 trys!

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

# Define the array of principal amounts and the interest rate


a = [Link]([100, 500, 800])
r = 0.09

# Create an empty array to store the results


B = [Link]((3, 5)) # 3 rows for a, 5 columns for n values

# Loop through the values of n (2, 4, 6, 8, 10)


for idx, n in enumerate(range(2, 12, 2)):
B[:, idx] = a * (1 + r) ** n # Calculate and store the results

# Display the results matrix


print(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 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.

 value is the current element from the iterable.

2. range(2, 12, 2):


o Generates the sequence 2, 4, 6, 8, 10.
o enumerate() pairs these indices with an index 0 and increases by 1 with
each step.
3. How idx Increments:
o In each loop iteration, idx is automatically incremented by 1 because
enumerate() provides the next index in the sequence.
o Python handles this increment automatically; you don't have to
manually increase idx.
SKEE1033 33
VECTORIZING FOR LOOP
 Example 14: Iteration breakdown, walk through each interation in
details and show how the matrix B is filled with values
Initial Setup:

a = [Link]([100, 500, 800]) r = 0.09


B = [Link]((3, 5)) creates a 3x5 matrix filled with zeros:

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]]

• Each iteration updates a specific column in the matrix B with


calculated values based on a, r, and the corresponding n value.
• The final matrix B shows the results in a structured format with rows
representing the principal amounts and columns representing the
different years.

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

# Define the arrays of principal amounts and years


a = [Link]([100, 500, 800])
n = [Link]([2, 4, 6, 8, 10])
r = 0.09 # Define the interest rate

# Use meshgrid to create 2D arrays for vectorized calculations


N, A = [Link](n, a)

# Calculate the array B using element-wise operations


B = A * (1 + r) ** N Array A:
[[100 100 100 100 100]
# Display the arrays A, N, and the resulting array B [500 500 500 500 500]
print("Array A:") [800 800 800 800 800]]
print(A)
print("\nArray N:") Array N:
print(N) [[ 2 4 6 8 10]
print("\nResulting Array B:") [ 2 4 6 8 10]
print(B) [ 2 4 6 8 10]]

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

# Define smaller arrays for testing


a = [Link](1000, size=1000) # Reduced size for 'a’
n = [Link](2, 2002, 2) # Smaller range for 'n' to reduce complexity
r = 0.09

# 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):

# Measure time for the nested loop operation


start_time = [Link]()
B_loop = [Link]((len(a), len(n))) # Initialize B with zeros for loop assignment
for i in range(len(a)):
for j in range(len(n)):
B_loop[i, j] = a[i] * (1 + r) ** n[j]
time2 = [Link]() - start_time

# Display elapsed times for both methods


print(f"Array Operation Elapsed Time: {time1:.4f} seconds")
print(f"Loop Elapsed Time: {time2:.4f} seconds") Based on the resulting
elapse time, it shows that
the loop statement for
this program consume
almost double the time
compared to the array
operation method.
Array Operation Elapsed Time: 0.0379 seconds
Loop Elapsed Time: 2.1045 seconds

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

# Define the array of income values


inc = [Link]([4000, 12000, 18000, 23000, 30000])

# Calculate the tax components without loops or decision statements


tax1 = (0.1 * inc) * (inc <= 10000)
tax2 = (1000 + 0.2 * (inc - 10000)) * (inc > 10000) * (inc <= 20000)
tax3 = (3000 + 0.5 * (inc - 20000)) * (inc > 20000)

# Sum the tax components to get the total tax for each income
tax = tax1 + tax2 + tax3

# Display the income and corresponding tax values


print(f"Income: {inc}")
print(f"Tax: {tax}")

Income: [ 4000 12000 18000 23000 30000]


Tax: [ 400. 1400. 2600. 4500. 8000.]

SKEE1033 44
CONTROL FLOW DRILL

1) Draw the flow chart of Example 3, Example 4 and Example 5.


2) Rewrite Example 7 with the following line removed from the code.
tax = tax1 + tax2 + tax3;
3) Rewrite Example 5 using logical vector method (without using any decision statement).
4) Write the pseudo-code for Example 7.
5) Draw the flow chart of Example 10, Example 11, Example 12 and Example 13.
6) Rewrite Example 10 for three values of V (3, 6 and 9) and return Q and T as matrices with
three rows where each row correspond to each V value.
7) Rewrite Example 12 without the continue statement.
8) Rewrite Example 12 by replacing the for statement with while statement.
9) Rewrite Example 13 without the break statement.
10) Rewrite Example 14 in order to swap a to column direction and n to row direction.
11) If the output B of Example 15 is to be shown to a customer, tabulate B in a normal table.
12) Rewrite Example 15 with array operation when r is also having several values. For example,
let r=[0.08,0.09]. (Hint: explore [Link]).
13) Trace the outputs for every assignment statement in Example 17.

SKEE1033 45

You might also like