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

Python Conditional Statements Guide

This document covers structured programming in Python, focusing on conditional statements such as if, if...else, and if...elif structures, as well as loops including while and for loops. It explains the syntax and usage of these constructs, including logical and relational operators, and provides examples for clarity. Additionally, it touches on debugging techniques using the Spyder debugger to identify and fix errors in code.

Uploaded by

chiapaul980
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

Python Conditional Statements Guide

This document covers structured programming in Python, focusing on conditional statements such as if, if...else, and if...elif structures, as well as loops including while and for loops. It explains the syntax and usage of these constructs, including logical and relational operators, and provides examples for clarity. Additionally, it touches on debugging techniques using the Spyder debugger to identify and fix errors in code.

Uploaded by

chiapaul980
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

SECTION 5:

STRUCTURED
PROGRAMMING IN PYTHON
ENGR 103 – Introduction to Engineering Computing
2 Conditional Statements
• if statements
• Logical and relational operators
• if…else statements

Webb ENGR 103


The if Statement
3

 We’ve already seen the if structure


 If X is true, do Y, if not, don’t do Y
 In either case, then proceed to do Z

 In Python:
if condition:
statements

 Statements are executed if condition is True


 Statement block defined by indenting those lines of code
 Condition is a logical expression
 Boolean - either True or False
 Makes use of logical and relational operators
 May use a single line for a single statement:
if condition: statement
Webb ENGR 103
Logical and Relational Operators
4

Operator Relationship or Logical Operation Example

== Equal to x == b
!= Not equal to k != 0
< Less than t < 12
> Greater than a > -5
<= Less than or equal to 7 <= f
>= Greater than or equal to (4+r/6) >= 2
AND – both expressions must evaluate to
and true for result to be true
(t > 0) and (c == 5)

OR – either expression must evaluate to


or true for result to be true
(p > 1) or (m > 3)

NOT– negates the logical value of an


not expression
not (b < 4*g)
Webb ENGR 103
The if…else Structure
5

 The if … else structure


 Perform one process if a condition
is true
 Perform another if it is false

 In Python:
if condition:
statements1
else:
statements2

 Note that if and else code


blocks are defined by indents
Webb ENGR 103
The if…elif…else Structure
6

 The if … elif … else structure


 If a condition evaluates as false, check another condition
 May have an arbitrary number of elif statements

 In Python:
if condition1:
statements1
elif condition2:
statements2
else:
statements3
Webb ENGR 103
The if…else, if…elif…else Structures
7

 Some examples:

 Note that code blocks are defined by indents


 Each line must have the same indent - use the Tab key
 Meaningful whitespace is a distinguishing characteristic of Python
 Other languages use brackets or end statements
Webb ENGR 103
The if…elif Structure
8

 We can have an if
statement without an else
 Similarly, an if…elif
structure need not have an
else
 In Python:
if condition1:
statements1:
elif condition2:
statements2
Webb ENGR 103
9 while Loops

Webb ENGR 103


The while loop
10

 The while loop


 While X is true, do A
 Once X becomes false, proceed to B

 In Python:
while condition:
statements

 Statements are executed as long as


condition remains true
 Condition is a logical expression
 Whitespace (indent) defines while block
Webb ENGR 103
while Loop – Example 1
11

 Consider the following while loop example


 Repeatedly increment x by 7 as long as x is less than or equal to 30
 Value of x is displayed on each iteration

 x values displayed: 19, 26, 33


 x gets incremented beyond 30
 All loop code is executed as long as the condition was true at the
start of the loop

Webb ENGR 103


The break Statement
12

 Let’s say we don’t want x to increment beyond 30


 Add a conditional break statement to the loop

 break statement causes loop exit before executing all code


 Now, if (x+7)>30, the program will break out of the loop and
continue with the next line of code
 x values displayed: 19, 26
 For nested loops, a break statement breaks out of the current
loop level only
Webb ENGR 103
while Loop – Example 1
13

 The previous example could be simplified by modifying the


while condition, and not using a break at all

 Now the result is the same as with the break statement


 x values displayed: 19, 26
 This is not always the case
 The break statement can be very useful
 May want to break based on a condition other than the loop condition
 break works with both while and for loops

Webb ENGR 103


while Loop – Example 2
14

 Next, let’s revisit the while loop


examples from Section 4
 Use input() to prompt for input
 Use print() to return the result

Webb ENGR 103


while Loop – Example 3
15

 Here, we use a while loop to


calculate the factorial value of a
specified number

Webb ENGR 103


while Loop – Example 3
16

 Add error checking to ensure that x


is an integer
 One way to check if x is an integer:

Webb ENGR 103


while Loop – Example 3
17

 Another possible method for


checking if x is an integer:

Webb ENGR 103


Infinite Loops
18

 A loop that never terminates is an infinite loop


 Often, this unintentional
 Coding error
 Other times infinite loops are intentional
 E.g., microcontroller in a control system
 A while loop will never terminate if the while condition
is always true
 By definition, True is always true:

while True:
statements repeat infinitely

Webb ENGR 103


while True
19

 The while True syntax can be used in conjunction with a


break statement, e.g.:

 Useful for
multiple break
conditions
 Control over
break point
 Could also
modify the while
condition

Webb ENGR 103


20 for Loops

Webb ENGR 103


The for Loop
21

 The for loop


 Loop executed a specified number of times

for var in iterable:


statements

 iterable: any iterable object (ndarray, list, tuple,
dict, str)
 var: variable that assumes each successive value in
iterable on each iteration
 Statements: code block that is executed once for
each item in iterable

 Collection-based, not counter-based


 Iterates through each item in a collection
 Can be counter-based, like flowchart to the right

Webb ENGR 103


for Loop – Example 1
22

 A collection-based (or iterator-


based) for loop
 Iterates through each value in a list
of days
 No explicit loop counter

Webb ENGR 103


for Loop – Example 2 – range()
23

 Counter-based for loop


 Use Python's range() function:
range(start, stop, step)
 Generate a list of loop counter values to
iterate through
 Technically, still collection-based

Webb ENGR 103


for Loop – Example 3 – enumerate()
24

 Sometimes we may want a combination of a collection-


based and counter-based for loop
 Iterate over both the values and indices of all items in an iterable
 Use Python's enumerate() function
 Generates an (index, value) pair for each item in the iterable

 For example, consider a list of numbers:


x = [2, 4, 6, 8, 10]
 Generate (index, value) pairs for each item in x:
i, val = enumerate(x)
 Generates the following (i, val) pairs:
(0, 2), (1, 4), (2, 6), (3, 8)
 Can iterate over these (index, value) pairs with a for loop
Webb ENGR 103
for Loop – Example 3 – enumerate()
25

 Loop through an array of numbers to


find the maximum value and its index
 Use enumerate() to simultaneously
loop through array values and their
indices

Webb ENGR 103


Exercise – for Loop, enumerate()
26

 The step response of a first-order system is given by


𝑡𝑡

𝑦𝑦 𝑡𝑡 = 1 − 𝑒𝑒 𝜏𝜏

 Write a script to do the following:


 Generate an array of 𝜏𝜏 values:
Exercise

𝜏𝜏 = 1.0 1.5 2.0 2.5 3.0 𝑠𝑠𝑠𝑠𝑠𝑠


 Generate a time vector with 2000 values between 0 and
5 ∗ max 𝜏𝜏
 In a for loop, using the enumerate function, iterate
through the values in 𝜏𝜏 and:
 Calculate 𝑦𝑦 𝑡𝑡
 Store the result as one column of a matrix, y
 Outside of the for loop, plot each of the columns of y on
a single set of axes

Webb ENGR 103


27 Nested Loops

Webb ENGR 103


Nested Loop – Example 1
28

 Use a nested for loop to find the maximum value in a


matrix or 2-D array
 Outer loop steps through rows
 Inner loop steps through columns
 Store the largest value seen as the maximum value
 Consider an (m×n) matrix, A
 A[0] indexes the first row, so
for row in A:
 Steps through the rows in A one-by-one
 row = A[0], row = A[1], up to row = A[-1]
 An inner loop steps through each element in each row
for row in A:
for val in row:
<code to check for max>
 val = row[0], val = row[1], and so on
Webb ENGR 103
Nested Loop – Example 1
29

Webb ENGR 103


Nested for Loop – Example 2
30

 Evaluate a function of two variables:


−𝑥𝑥 2 −𝑦𝑦 2
𝑧𝑧 = 𝑥𝑥 ⋅ 𝑒𝑒
over a range of −2 ≤ 𝑥𝑥 ≤ 2 and −2 ≤ 𝑦𝑦 ≤ 2

 A surface in three-
dimensional space
 Later in the course, we’ll
learn how to generate
such a plot

Webb ENGR 103


Nested for Loop – Example 2
31

−𝑥𝑥 2 −𝑦𝑦 2
𝑧𝑧 = 𝑥𝑥 ⋅ 𝑒𝑒
 Evaluate the function over a range of 𝑥𝑥 and 𝑦𝑦
 First, define x and y
vectors
 Initialize the Z matrix
 Use a nested for loop
to step through all
points in this range of
the x-y plane
 Use enumerate() to
iterate through
indices and values

Webb ENGR 103


Nested Loops
32

 We just saw how we can use nested loops to:


 Find the maximum value in a matrix or 2-D array
 Evaluate a function of two variables
 A good illustration of nested loops, BUT
 There are easier, more efficient ways to do both of these
things in Python
 Looping is slow – avoid if possible
 Operate directly on arrays

Webb ENGR 103


33 The Spyder Debugger

Webb ENGR 103


Debugging
34

 You’ve probably already realized that it’s not uncommon for your
code to have errors
 Computer code errors referred to as bugs
 Three main categories of errors
 Syntax errors prevent your code from running and generate a Python
error message
 Runtime errors – not syntactically incorrect, but generate an error upon
execution – e.g., indexing beyond matrix dimensions
 Algorithmic errors don’t prevent your code from executing, but do
produce an unintended result
 Syntax and runtime errors are usually more easily fixed than
algorithmic errors
 Debugging – the process of identifying and fixing errors is an
important skill to develop
 Spyder has a built-in debugger to facilitate this process

Webb ENGR 103


Debugging
35

 Identifying and fixing errors is difficult because:


 Programs run seemingly instantaneously
 Incorrect output results, but can’t see the intermediate
steps that produced that output

 Basic debugging principles:


 Slow code execution down – allow for stepping through
line-by-line
 Provide visibility into the code execution – allow for
monitoring of intermediate steps and variable values

Webb ENGR 103


Spyder Debugger – Breakpoints
36

 Breakpoint – specification of a line of code at which


Spyder should pause execution
 Set by clicking next to the number to the left of a
line of code in a script
 Spyder will execute the script up to this line, then pause

 Clicking here sets a


breakpoint
 Indicated by red
circle

Webb ENGR 103


Spyder Debugger – Breakpoints
37

 Click 'Debug file' to begin


execution
 Execution halts at the
breakpoint
 Before executing that line

 Console prompt changes


to IPdb [n]:
 Cannow interactively
enter commands

Webb ENGR 103


Spyder Debugger – Breakpoints
38

 Click 'Run current line' to


execute the current line
of code
 Arrow indicator advances
to the next line
 Variable, m, defined on
previous line (line 16)
now exists in the
namespace
 Available in the console

Webb ENGR 103


Debugger – Example
39

 Recall a previous example of an algorithm to square every


element in a matrix
 Let’s say we run our script and get the following result:

 Resulting matrix is transposed


 Use the debugger to figure out why
Webb ENGR 103
Debugger – Example
40

 Set a breakpoint in the


innermost for loop
 Click 'Debug file'
 Code executes up to the
breakpoint
 Variable Explorer shows
i=0 and j=0
 Click 'Run current line'
 Display B[i,j] and
C[i,j] in the console
 Both are as expected

Webb ENGR 103


Debugger – Example
41

 Click 'Run current line'


twice
 Execute the next
iteration of the loop
 Now, i=0 and j=1
 First row, second column
 B[i,j] = 10
 But, C[i,j] = 16
 Should be 100

Webb ENGR 103


Debugger – Example
42

 We see that C[1,2] = 16 = 4**2 = B[2,1]**2


 This leads us to an error on line 21 of the code
 Should be B[i,j]**2, not B[j,i]**2

Webb ENGR 103


Exercise – Nested Loops, Debugger
43

 Write a script to do the following:


 Create a 5x5 matrix of zeros, X
 Initialize a random number generator:
rng = [Link].default_rng()
In a nested loop step through all elements in X
Exercise

 Outer loop steps through rows, inner loop steps through


columns
 Replace each element in X with a random integer:
X[i,j] = [Link](100)

 Set a breakpoint at the start of the outer loop and


run the debugger
 Step through code line-by-line observing the
evolution of the matrix X
Webb ENGR 103

You might also like