1/48
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
selection (or decision) structure
decision making capability of a computer
- illustrates how decisions can be made when presented with two or more options
relies on if, can use elif or else
condition
describes the question upon which the decision must be made
based on the evaluation of the condition
the result must yield a Boolean answer (true or false)
Boolean expression
expression which is either true or false
x == y (equal)
x =! y (not equal)
x>y (x is greater than y)
x<y (x is less than y)
x>= y (x is greater than or = to y)
x <= y( x is less than or = to y)
simple (dual- alternative) selection structure
simple if/else statement
single alternative selection (null else branch) structure
no else statement
nested selection
allows more than one condition to be checked with multiple elif statements
Dual-alternative selection structure
occurs when a choice is made between two alternate paths depending on the result of a condition between true or false
- ident instructions within the selection structure
keywords: if, else
example of dual-alternative
average_gpa = 3.7
if average_gpa> 3.8:
print('Scholarship Eligible')
else:
print('Scholarship inelgible')
indentation matters
indentation is important because it tells you what to print after the if/else statement is passed
two common errors
when learning selection statements in python, two common errors include
- forgetting the colon at the end of the condition
- incorrect indentation
single line selection expression with ternary operation
- use of ternary operation allows the if/else code to be simplified to one line
- syntax: [on_true] if [expression] else [on_false]
example of single line selection expression with ternary operation
average_gpa = 3.7
print('Scholarship Eligible') if average_gpa > 3.8 else print('Scholarship Ineligible') == ONE LINE
single-alternative selection (Null Else Branch)
- occurs when the false branch is not needed
- nothing will happen if condition is false (no else)
- used when a task should be performed only when it is true
if it is false nothing happens
python keyword : if
example of single-alternative selection (Null Else Branch)
student_gpa = 3.9
if student_gpa >= 3.7
award_scholarship = True
Nested selection
- multiple alternative selection structures to decide based on multiple pathways
- used when it is necessary to determine which task to perform among multiple choices
- indent instructions within the selection structure
- python keywords: if, elif, else
nested selection (example)
richter_value = 7.5
if richter_value > 8.0:
print('Most structures fall')
elif richter_value >= 7.0:
print('Many buildings destroyed')
elif richter_value >= 6.0:
print('Many buildings damaged')
else:
print('No destruction caused')
nested selection ---
selection statements can be nested within each other
compound conditions
uses an if statement with and or or connector to test multiple conditions
compound conditions (AND)
uses an if statement with AND connector to test multiple conditions
python keywords: if, and
compound conditions example
- this surcharge will only go through if the student is completing more than 15 credits AND Is an undergraduate students
- both conditions must be true (otherwise subcharge will not occur)
if num_credits > 15 and student_type = 'Undergraduate':
student_surcharge = 500
compound conditions (AND) (Cont'd)
condition 1 & condition 2
truth table for the AND logical Operator
both statements have to be true for it to run
compound conditions (OR)
uses an if statement with OR connector to test multiple conditions
python keywords: if, or
example
- This surcharge will go through ifeither the student is completingmore than 15 credits OR is agraduate student (or both)
- If both conditions are found to befalse, the surcharge will not occur
if num_credits > 15 or student_type = 'Graduate':
student_surcharge = 500
common errors with and & or
- confusing AND and OR
- there is no golden rule (try to think carefully about logic & test the result with various values)
logical negation (NOT)
if expression is true --> logical result is false
if expression is false -->
logical result is true
if not ( 1 == 2):
print('(1==2) is False. So Not False is True')
selection statements and the in operator
* the in operator can be used to check if a value is within a list
today = 'Mon'
if today in ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri']
print('Today is a weekday')
else:
print('Today is a weekend')
Repetition Overview
most programs require the same logic to be repeated for several sets of data (ex. coin counting ==> keep counting until there are no more coins to count)
- the most efficient way to deal with this situation is to establish a looping structure in the algorithm which will cause the processing logic to be repeated a number of times
loop
a method of performing a task more than once (repeating instructions)
iteration
one cycle of executing statments within a loop
in python there are two different ways to loop
- a counted number of times (definite/counted)
- using a logical expression (indefinite loop)
repetition example
N = 5
You ask the question n>0
If n is > 0 you print n - 1 and you do this until n is not greater than 0
So when you get to a negative value and the n>0 = no
You print Blastoff!
using while loops
flow of execution:
- evaluate the expression yielding True or False
- if the expression is true
* execute each of the statements within the body and keep checking the origianl conditions
False
- exit the entire loop and ignore the body
- just print out what is after that body
example: while loop
x = 5
while x>3:
print(x)
x -= 1
print('Keep going with the rest')
Infinite Loops
be careful of the logic you use in the loop body!
n = 5
while n>0:
print('Lather')
print('Rinse')
print('Dry off')
if you do
n = 0
while n>0:
print('Lather')
print('Rinse')
print('Dry off')
0 is not > 0
so it doesn't run continually
nested loops
loops can be nested within each other
x = 5
while x != 1
print(x)
while x>3:
print( 'x > 3')
x - = 1
x -= 1
Counted (Definite) Loops
often, you will have a finite set of items
- a loop can be used to run through each item in the set
- they run a specific number of times
using for loops
flow of execution:
- the expression_list is evaluated once, it should yield an iterable object (ex. list, tuple, etc)
- for each member in the expression_list, execute all statements in the loop body
- the iteration variable iterates through the sequence (ordered set)
- the loop body is executed once for each element in the sequence
- the iteration variable's value is changed on each iteration in the sequence
for loop example
for i in [5,4,3,2,1]:
print(i)
print('Blastoff!')
- it goes through the list and evaluates each one after its done it prints Blastoff!
for loop example 2
for i in [5,4,3,2,1]
if i%2 == 0:
print(f' {i} is even')
else:
print(f' {i} is odd')
print('Blastoff!')
using for loops with ranges
- in addition to processing lists, loops can be used to iterate based on a range
for number in range(3):
print(number)
0
1
2
- prints the values within the defined range
range definition
range (6,0,-2)
you start at 6 and end at 0 and you subtract -2 until you get to 0
for vs while
you use for when you know how many times you want the loop to run
- if you are required to repeat some computation until the condition is met ==> while loop
nested loops (loops can be nested within each other)
for i in [1,2,3]:
for j in [1,2,3]:
print(i*j)
print('Blastoff!')
- Trace the loop
You are going to trace
For each i within [1,2,3]
This iteration i = 1
J =1
While j = 1 is <= 1
Print (i) which is 1
Now you increment 1 += 1 so j is now 2
Is j =2 no
So go back to i =2
Now j is back to = 1
1 <= 2
So print (i)
Now increment j which is now 2
Now 2 < = 2
print(i)
Now make j = 3
Multiple sets of commands
When j = 4 you see that 4<= i (3)
You then exit and print Blastoff!
2 & 3 print multiple times because of the logic
use of end in print() statements
by default, the print()
function adds a line break at the end
to change the default and print a different character, such as a space, specify a value for end in print() function
algorithms: find the largest
values = [3, 41, 12, 9, 74,15]
largest = values[0]
for curr_value in values:
if curr_value > largest = curr_value
print(f'The largest value is {largest}.')
algorithms: summing values
to sum values, an accumulator must be created
- the value of the current item in the list added to the accumulator (running total)
values = [3, 41, 12, 9, 74, 15]
total = 0
for curr_value in values:
total += curr_value
print(f'The sum is {total}.')
algorithms: finding the mean in values
* once the sum is found, the average can be found with the len function
* be careful of divide by 0!
values = [3,41,12,9,74,15]
total = 0
for curr_value in values:
total += curr_value
if len(values) > 0:
print(f' The average is {total/len(values):.1f}.')
else:
print('Cannot computer the mean for an empty list.')
algorithms: counting values
* to count values, an additional counter must be created.
* 1 is added to the counter each the specified criteria is met
values = [3, 41, 12, 9, 74, 15]
num_high_scores = 0
high_score = 20
for curr_value in values:
if curr_value > high_score
num_high_scores += 1
print(f'The number of high scores is {num_high_scores}.')
algorithms: linear search
• To find if a value is in a list, one way is to search each element in thelist, one at a time (linear search)
• Continue searching until one of the following things happens:- The value being searched for was found- There are no other values to search
values = [3, 41, 12, 9, 74, 15]
found = False
curr_index = 0
search_value = 12
while not found and curr_index < len(values):
if values[curr_index] == search_value:
found = True
else:
curr_index += 1
if found:
print('The element was found')
else:
print('The element was not found')