Laboratory 7: Selection Structures
Juans-MacBook-Pro.local
juanandreszuluqga
/Users/juanandreszuluqga/anaconda3/bin/python
3.11.4 (main, Jul
5 2023, 09:00:44) [Clang 14.0.6 ]
sys.version_info(major=3, minor=11, micro=4, releaselevel='final', serial=0)
Full name: Juan Zuluaga
R#: 11830028
Title of the notebook: Lab 7
Date: 09/24/23
Algorithm Building Blocks
All programs are made up of three fundamental patterns of control or flow:
1.
Sequence
- one instruction after another
2.
Selection (Conditional)
- A group of instructions may or may not be executed, depending on some condition
3.
Repetition (Loop)
– A group of instructions repeated multiple times
Conditional Execution
Conditional statements are logical expressions that evaluate as TRUE or FALSE and using these results to perform further operations based on these conditions. All flow control in a program depends on
evaluating conditions. The program will proceed diferently based on the outcome of one or more conditions - really sophisticated AI programs are a collection of conditions and correlations. Amazon knowing
what you kind of want is based on correlations of your past behavior compared to other peoples similar, butmore recent behavior, and then it uses conditional statements to decide what item to offer you in your
recommendation items. It's spooky, but ultimately just a program running in the background trying to make your money theirs.
Conditional Execution: Comparison
The most common conditional operation is comparison. If we wish to compare whether two variables are the same we use the == (double equal sign).
For example x == y means the program will ask whether x and y have the same value. If they do, the result is TRUE if not then the result is FALSE.
Other comparison signs are
!=
does NOT equal,
<
smaller than,
>
larger than,
<=
less than or equal, and
>=
greater than or equal.
There are also three logical operators when we want to build multiple compares (multiple conditioning); these are
and
,
or
, and
not
.
The
and
operator returns TRUE if (and only if)
all
conditions are TRUE. For instance
5 == 5 and 5 < 6
will return a TRUE because both conditions are true.
The
or
operator returns
TRUE
if at least one condition is true. If
all
conditions are FALSE, then it will return a FALSE. For instance
4 > 3 or 17 > 20 or 3 == 2
will return
TRUE
because the first
condition is true. The
not
operator returns
TRUE
if the condition after the
not
keyword is false. Think of it as a way to do a logic reversal.
x =:
7 y =:
10
x is equal to y :
False
x is not equal to y :
True
x is greater than y :
False
x is less than y :
True
5 == 5 and 5 < 6 ?
True
4 > 3 or 17 > 20
True
not 5 == 5 False
Conditional Execution: Block `if` statement
The
if
statement is a common flow control statement. It allows the program to evaluate if a certain condition is satisfied and to perform a designed action based on the result of the evaluation. The structure
of an
if
statement is
if condition1 is met:
do A
elif condition 2 is met:
do b
elif condition 3 is met:
do c
else:
do e
The
elif
means "else if". The
:
colon is an important part of the structure it tells where the action begins. Also there are no scope delimiters like (), or {} . Instead Python uses indentation to isolate blocks of
code.
This convention is hugely important - many other coding environments use delimiters (called scoping delimiters), but Python does not. The indentation itself is the scoping delimiter.
The next code fragment illustrates illustrates how the
if
statements work. The program asks the user for input. The use of
raw_input()
will let the program read any input as a string so non-numeric
results will not throw an error. The input is stored in the variable named
userInput
. Next the statement if
userInput == "1":
compares the value of
userInput
with the string
"1"
. If the value in
the variable is indeed \1", then the program will execute the block of code in the indentation after the colon. In this case it will execute
print "Hello World"
print "How do you do? "
Alternatively, if the value of
userInput
is the string
'2'
, then the program will execute
print "Snakes on a plane "
For all other values the program will execute
print "You did not enter a valid number"
Enter the number 1 or 22
Snakes on a plane
Conditional Execution: Inline `if` statement
An inline
if
statement is a simpler form of an
if
statement and is more convenient if you only need to perform a simple conditional task. The syntax is:
do TaskA `if` condition is true `else` do TaskB
An example would be
myInt = 3
num1 = 12 if myInt == 0 else 13
num1
An alternative way is to enclose the condition in brackets for some clarity like
myInt = 3
num1 = 12 if (myInt == 0) else 13
num1
In either case the result is that
num1
will have the value
13
(unless you set myInt to 0).
One can also use
if
to construct extremely inefficient loops.
12
Example: Pass or Fail?
Take the following inputs from the user:
1. Grade for Lesson 1 (from 0 to 5)
2. Grade for Lesson 2 (from 0 to 5)
3. Grade for Lesson 3 (from 0 to 5)
Compute the average of the three grades. Use the result to decide whether the student will pass or fail.
Enter the grade for Lesson 12
Enter the grade for Lesson 25
Enter the grade for Lesson 35
Average Course Grade: 4.0
Failed
Here are some great reads on this topic:
"Common Python Data Structures (Guide)"
by
Dan Bader
available at *
https://realpython.com/python-data-structures/
"Data Structures You Need To Learn In Python"
by
Akash
available at *
https://www.edureka.co/blog/data-structures-in-python/
"Data Structures in Python— A Brief Introduction"
by
Sowmya Krishnan
available at *
https://towardsdatascience.com/data-structures-in-python-a-brief-introduction-b4135d7a9b7d
"Everything you Should Know About Data Structures in Python"
by
ANIRUDDHA BHANDARI
available at *
https://www.analyticsvidhya.com/blog/2020/06/data-structures-python/
"Conditional Statements in Python"
by
John Sturtz
available at *
https://realpython.com/python-conditional-statements/
"Python If Statement explained with examples"
by
CHAITANYA SINGH
available at *
https://beginnersbook.com/2018/01/python-if-statement-example/
Here are some great videos on these topics:
"Python: Data Structures - Lists, Tuples, Sets & Dictionaries tutorial"
by
Joe James
available at *
https://www.youtube.com/watch?v=R-HLU9Fl5ug&t=92s
"Python Tutorial for Beginners 5: Dictionaries - Working with Key-Value Pairs"
by
Corey Schafer
available at *
https://www.youtube.com/watch?v=daefaLgNkw0
"How to Use If Else Statements in Python (Python Tutorial #2)"
by
CS Dojo
available at *
https://www.youtube.com/watch?v=AWek49wXGzI
"Python If Statements | Python Tutorial #10"
by
Amigoscode
available at *
https://www.youtube.com/watch?v=wKQRmXR3jhc
Exercise: What to select?
Below is a multiple-alternative if statement to display a message indicating the success of a student for a given assignment on a grade scale of 5.
i.e., 1:fail, 2:bad, 3:satisfactory, 4:good, 5:excellent.
However this code is not functioning as expected. Why? Please correct the mistakes and make this code work.
* Make sure to cite any resources that you may use.
Enter the grade3
satisfactory
In [10]:
# Preamble script block to identify host, user, and kernel
import
sys
!
hostname
!
whoami
print
(
sys
.
executable
)
print
(
sys
.
version
)
print
(
sys
.
version_info
)
In [11]:
# Compare
x
=
7
y
=
10
print
(
"x =: "
,
x
,
"y =: "
,
y
)
print
(
"x is equal to y : "
,
x
==
y
)
print
(
"x is not equal to y : "
,
x
!=
y
)
print
(
"x is greater than y : "
,
x
>
y
)
print
(
"x is less than y : "
,
x
<
y
)
In [12]:
# Logical operators
print
(
"5 == 5 and 5 < 6 ? "
,
5
==
5
and
5
<
6
)
print
(
"4 > 3 or 17 > 20 "
,
4
>
3
or
17
>
20
)
print
(
"not 5 == 5"
,
not
5
==
5
)
In [13]:
# Block if example
userInput
=
input
(
'Enter the number 1 or 2'
)
# Use block if structure
if
userInput
==
'1'
:
print
(
"Hello World"
)
print
(
"How do you do? "
)
elif
userInput
==
'2'
:
print
(
"Snakes on a plane "
)
else
:
print
(
"You did not enter a valid number"
)
In [14]:
myInt
=
0
num1
=
12
if
(
myInt
==
0
)
else
13
num1
Out[14]:
In [15]:
Lesson1
=
int
(
input
(
'Enter the grade for Lesson 1'
))
Lesson2
=
int
(
input
(
'Enter the grade for Lesson 2'
))
Lesson3
=
int
(
input
(
'Enter the grade for Lesson 3'
))
Average
=
int
(
Lesson1
+
Lesson2
+
Lesson3
)
/
3
print
(
'Average Course Grade:'
,
Average
)
if
Average
>=
5
:
print
(
"Passed"
)
else
:
print
(
"Failed"
)
In [16]:
# Block if example
userInput
=
input
(
'Enter the grade'
)
# Convert userInput to an integer
userInput
=
int
(
userInput
)
# Use block if structure
if
userInput
==
1
:
print
(
"FAIL"
)
elif
userInput
==
2
:
print
(
"bad"
)
elif
userInput
==
3
:
print
(
"satisfactory"
)
elif
userInput
==
4
:
print
(
"good"
)
elif
userInput
==
5
:
print
(
"excellent"
)
else
:
print
(
"ERROR"
)
In [ ]: