0% found this document useful (0 votes)
7 views43 pages

Flow Control & NumPy Vectorization Guide

Vectorization physicology

Uploaded by

theodore.anton
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)
7 views43 pages

Flow Control & NumPy Vectorization Guide

Vectorization physicology

Uploaded by

theodore.anton
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

ENCMP 100 - COMPUTER PROGRAMMING FOR ENGINEERS

Topic 5: Flow Control Statements, NumPy Vectorization


Recall the four types of procedural program flow

2
Outline
Conditional Statements:
o if statement: Executes a block of code if a condition is true.
o if...else statement: Executes one block of code if the condition is true and
another if it's false.
o if...elif...else statement: Executes different blocks of code depending on which
condition is true.

Loop Statements:
o for loop: Iterates over a sequence (such as lists, tuples, strings, etc.) and
executes a block of code for each item.
o while loop: Repeatedly executes a block of code as long as a condition is true.

Jump Statements:
o break statement: Exits the loop prematurely, skipping the remaining iterations.
o continue statement: Skips the current iteration of a loop and continues with the
next iteration.
o pass statement: Placeholder statement that does nothing, used in situations
where a statement is syntactically required but no action is needed.
3
The if...elif...else statement

elevatorsim

Program flowchart

4
Example [Link]

Approach 1: Using only if statements Approach 2: Using elif and else

Readability: Code using elif and else is typically more readable and understandable. It
clearly conveys the hierarchical nature of the conditions being checked.
Efficiency: With elif and else, once a condition is satisfied, the remaining conditions are
not evaluated. This can improve the efficiency of the code, especially if there are many
conditions to check.
5
Example: Rock-paper-scissors game
Game Content:
Prompt for choices: 0--Rock, 1--Scissors, 2--Paper
Choices: Player: Manually choose, Computer: Automatically choose
Determine and display the outcome: Player wins, draw, computer wins

6
Example: Rock-paper-scissors game
Game Content:
Prompt for choices: 0--Rock, 1--Scissors, 2--Paper
Choices: Player: Manually choose, Computer: Automatically choose
Determine and display the outcome: Player wins, draw, computer wins

Rock_paper_scissors.txt
7
Nested ‘if’ statement

8
Example of the nested ‘if’ statement

Nested_if.txt

9
Ternary Operator
The ternary operator makes code more concise and is suitable for
simple conditional expressions.

Syntax:

This operator works by evaluating the condition (<condition>). If


the condition is true, it returns the value of <expression1>;
otherwise, it returns the value of <expression2>.

10
Examples of the ternary operator

[Link]

11
Piecewise-defined function

sale

f(x) represents the discounted price:

If the original price x is less than 128, a discount rate of 0.92 is applied.
If the original price x is 128 or more, a discount rate of 0.84 is applied.

12
match…case…

The match...case statement enables pattern matching, providing an


alternative to the if...else statement.

Syntax: match_case

The match-case syntax is a feature introduced in Python 3.10


and later versions. 13
for loop
a for loop is used to iterate over a sequence (such as a list, tuple,
string, or range) or any other iterable object.

for loop is a counting loop, not a conditional loop

14
Examples

[Link]

15
range() function
range(start, stop, step)
start: An optional parameter indicating the starting value of the sequence. It
defaults to 0.
stop: A required parameter indicating the end value of the sequence (exclusive).
step: An optional parameter indicating the step or increment between each
integer in the sequence. It defaults to 1. [Link]

16
while loop
a while loop is a control flow statement that allows code to be
executed repeatedly based on a condition.

a while loop is useful when you don’t know in advance how many
times you need to loop and instead rely on a changing condition. In
contrast, a for loop is typically used when you know the exact range
or collection to loop over.

17
Examples

[Link]

18
Nesting selection in repetition
Nesting selection in repetition is a concept where we use conditional
statements (like if, else if, and else) within loops (such as for or while
loops). This approach is helpful when we need to make decisions within
repetitive tasks. give some common examples

For example: grades

 Finding even or odd numbers in a range


 Grade classification based on score
 Checking for prime numbers in a range
 Validating user inputs in a loop
 Printing patterns with conditions

19
Nesting repetition in repetition (nested loops)
Nested loops are useful in situations where you need to perform a
repetitive task within another repetitive task. They allow you to iterate
over multiple dimensions of data or perform complex operations on a
set of data.

For example:
 print a multiplication table from 1 to 9
 Printing Patterns
 Generating Combinations
 Calculating Factorials

20
Nested ‘for’ loop examples

[Link]

21
Nested ‘while’ loop implementations

[Link]

22
Hand tracing a loop vs. using debugging tools

Sum of Digits

23
Sentinel values
Sentinel

Sentinel values are often used:

• When you don’t know how many items are in a list, use a ‘special’
character or value to signal the “last” item

• For numeric input of positive numbers, it is common to use the value


-1

A sentinel value denotes the end of a data set, but it is not part of
the data.

24
Jump Statements in a loop

1. break statement:
o When encountered within a loop, the break statement immediately
terminates the current loop and jumps out of it, skipping any remaining
iterations.

o It is primarily used to exit a loop prematurely when a certain condition is


met, without waiting for the loop to finish its normal iterations.

25
Example

[Link]

26
Jump Statements in a loop

2. continue statement:

o When encountered within a loop, the continue statement immediately skips the
rest of the current iteration and proceeds with the next iteration of the loop.

o It is mainly used to skip certain iterations of the loop based on certain


conditions, while continuing with the rest of the iterations.

27
Example

[Link]

28
Jump Statements in a loop

3. pass statement:

o The pass statement is a null statement that is syntactically valid but does
nothing when executed.
o It is primarily used as a placeholder in situations where a statement is
required by the syntax but no action is needed.
o It allows you to temporarily leave a code block empty without causing any
errors.
o Typically used in early stages of code development or as a placeholder for
future implementation within functions, classes, or loops.

29
Example

[Link]

30
while...else & for...else
In Python, loops can be combined with the else statement. In this case, the
code indented under the else clause is executed when the loop
completes its iterations without being interrupted by a break statement.

31
Examples

Else_in_loop.txt

32
Behavior of ‘else’ with ‘break’

Else_break.txt

33
Behavior of ‘else’ with ‘continue’

Else_continue.txt

34
NumPy vectorization vs. Looping

NumPy vectorization is the process of performing operations on


entire arrays at once, improving efficiency by avoiding loops.

• Looping: Uses iteration to perform repetitive tasks one at a


time; easy to understand but can be inefficient for large
datasets.

• Vectorization: Applies operations to entire arrays or datasets


at once; more efficient and concise but requires familiarity
with NumPy.

investment_loopi investment_vecto
ng rization

35
NumPy broadcasting

Broadcasting expands smaller-dimension arrays to match larger


ones, aligning arrays by expanding dimensions of size 1 so they can
operate together efficiently without copying data.

Example: For a 5x1 array and a 1x5 array:

The 5x1 array expands horizontally to 5x5.

The 1x5 array expands vertically to 5x5.

36
NumPy broadcasting

In NumPy, broadcasting is triggered when arrays have different


shapes but are still compatible for element-wise operations. Two
arrays can be broadcast together if their shapes meet these
conditions:

• Trailing Dimensions Match or Are 1: Starting from the last


dimension and moving backwards, the dimensions of both arrays
must either be the same or one of them must be 1.

• Automatic Expansion: If an array has a dimension of 1, it will


expand to match the other array's size in that dimension during
the operation.

broadcasting
37
NumPy broadcasting vs. looping
powertable_repeti
tion

powertable_broad
casting

38
NumPy random functions
[Link] functions can generate entire arrays of random values
in a single call, making them much faster and more memory-efficient
than repeatedly calling python built-in random functions.

numpy_random

39
NumPy vs. random: random number generation

[Link](1, 7, (2, 10)) generates a 2x10 array, where the


first row contains 10 random values for d1 (the first die) and the
second row contains 10 random values for d2 (the second die).
Note that 7 is exclusive.

This method eliminates the need for a loop to generate individual


random numbers for each die, making the code more concise and
efficient.

np_dice
dice

40
Optimizing Repetition with Selection: Loop vs.
Vectorized Approaches
MonteCarlo_np
MonteCarlo_loop

 Efficiency: The vectorized code is faster due to bulk operations with


NumPy.

 Simplicity: The vectorized code is more concise and easier to


understand.

 Performance: NumPy handles large-scale data better than loops in


Python.

41
Summary
 Control Flow:
o if Statement Syntax
if...else...
if...elif...else
o Nested if Statements
o Ternary Operator
 Loops:
o while Loop Syntax
o for Loop Syntax
o Nested Loop Syntax
o break, continue and pass Statements
o else Clause
o Behavior of else with break/continue
42
Summary

 NumPy vectorized programming:


o NumPy vectorization vs. Looping
o NumPy broadcasting
o NumPy random functions
o Optimizing repetition with selection using numpy vectorization

43

You might also like