04 Selection Structures
04 Selection Structures
3
Recap[2]
∙ Predict the output of the following program:
x = input("x: ")
y = input("y: ")
print(x, "+", y, "=", x+y)
∙ x: 17
∙ y: 19
∙ 17 + 19 = 1719
4
Recap[3]
Converting basic types: To convert a string to an integer or a real number, and
vice versa.
x = int(input("Input x"))
y = float(input("Input y:"))
print("x = ", x) Output
print("y = ", y) Input x:15
print("x+y = ", x+y) Input y:22
z = 'This is a string: "' + str(x+y) + '"' x = 15
print(z) y = 22.0
x+y = 37.0
This is a string: "37.0"
5
Recap[4]
Converting basic types
∙ int(), which takes a string and converts it to an integer. If the
argument is not a string representation of an integer, an error
occurs.
∙ float(), which takes a string and converts it to a "real" number
(also called *floating point number*, hence the name of the
function). If the argument is not a string representation of a real
number, an error occurs.
∙ str(), which takes a number (among other allowed types) and
converts it to a string.
6
What are True and False?
∙ They are not strings "True" and "False”
∙ Python uses these terms to represent truth values: true and false
∙ The following code runs without errors (note the absence of
quotation marks):
print(True)
print(False)
∙ Note: If we try to print arbitrary unquoted words, like:
print(Hello)
Python will cause a NameError
7
Comparison and logical operators
Here are the comparison operators that can be used on numbers
(and some other types, for example strings):
8
Comparison and logical operators
∙ When checking if the value of a variable x is undefined (i.e., it is
None), use
x is None
9
Conditions, True and False
∙ A condition is simply a bit of code that can produce a true or
false answer.
print(3 == 5) False
print(3 > 5) False
print(3 <=5) True
print(len("ATGC") > 5) False
print("GAATTC".count("T") > 1) True
print("ATGCTT".startswith("ATG")) True
print("ATGCTT".endswith("TTT")) False
print("ATGCTT".isupper()) True
print("ATGCTT".islower()) False
10
Constructing conditions[1]
∙ The basic building blocks are:
− equals (represented by ==)
− greater and less than (represented by > and <)
− greater and less than or equal to (represented by >=, <=)
− not equal (represented by!=)
− is a value in a list (represented by in)
− are two objects the same (represented by is)
11
Constructing conditions[2]
∙ Many data types also provide methods that return True or False
values, which are often a lot more convenient to use than the
building blocks above.
∙ For example:
− strings have a startswith method that returns true if the string
starts with the string given as an argument.
− “ACGTACT”.startswith(“AC”) returns True
∙ Note:
− the test for equality is two equals signs (==), not one.
Forgetting the second equals sign will cause an error.
12
Composite comparisons[1]
As we have seen, a < b is True if a is less than b and False otherwise:
print("1 < 2:", 1 < 2)
print("1 < 1:", 1 < 1)
print("2 < 1:", 2 < 1)
Output
1 < 2: True
1 < 1: False
2 < 1: False
13
Composite comparisons[2]
We can use composite comparisons as follows:
print("1 < 2 < 3:", 1 < 2 < 3)
print("1 < 2 < 1:", 1 < 2 < 1)
print("1 < 2 > 3:", 1 < 2 > 3)
print("1 < 2 > 1:", 1 < 2 > 1)
Output
1 < 2 < 3: True
1 < 2 < 1: False
1 < 2 > 3: False
1 < 2 > 1: True
14
14
A note on (in)equality operators[1]
The equality == and
print("False == 0:", False == 0)
inequality != operators
print(" type(False):", type(False))
ignore the types of data
print(" type(0):", type(0))
to a certain extent.
print(" type(False) == type(0):", type(False) == type(0))
print("True == 1:", True == 1)
Some languages (like
print(" type(True):", type(True))
PHP and JavaScript)
print(" type(1):", type(1))
have a strict equality
print(" type(True) == type(1):", type(True) == type(1))
operator === and strict
print("True != 2:", True != 2)
inequality operator !==
print(" type(True):", type(True))
that check both types and
print(" type(2):", type(2))
values of the compared
print(" type(True) == type(2):", type(True) == type(2))
objects. However,
Python doesn't have
that. 15
15
Python Control Structures[1]
∙ Any computer program can be written using the basic control structures.
∙ A control structure (or flow of control) is a block of program that analyses
variables and chooses a direction in which to go based on given parameters.
− In simple sentence, a control structure is just a decision that the computer
makes.
− So, it is the basic decision-making process in programming and flow of
control which determines how a computer program will respond when given
certain conditions and parameters.
∙ There are two basic aspects of computer programming: data and instructions.
− To work with data, you need to understand variables and data types;
− To work with instructions, you need to understand control structures and
statements.
− Flow of control through any given program is implemented with three basic
types of control structures: 16
● Sequential, Selection and Repetition.
16
Python Control Structures[2]
∙ The different control structures can be visualized as follows:
Repetition
17
17
Python Control Structures[3]
∙ Sequential execution is when statements are executed one after
another in order. You don't need to do anything more for this to
happen.
19
19
Conditionals[1]
∙ If we look back at the examples and exercises we have done until now:
− Absence of decision-making.
− Simple calculations on individual bits of data
− But each bit of data (a sequence for GC content) has been treated
identically.
− Real-life problems, however, often require our programs to act as
decision-makers
20
20
Conditionals[2]
∙ Decision making is one of the most important concepts of computer
programming.
− It requires that the developers specify one or more conditions to be
evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true,
and optionally, other statements to be executed if the condition is
determined to be false.
∙ Python programming language provides the following types of decision
making statements.
− if statements
− if....else statements
− if..elif..else statements
21
− nested if statements
21
Conditionals[3]
22
22
if statement
x=20
y=10
if x > y :
print(" X is bigger ")
23
if..else statement
x=10
y=20
if x > y :
print(" X is bigger ")
else :
print(" Y is bigger ")
∙ The else statement is to specify a block of code to be executed, if the condition in the if
statement is false. Thus, the else clause ensures that a sequence of statements is executed.
if expression:
statements
else: 24
statements 24
if..elif..else statement
if expression:
statements
elif expression: # While the previous expression is False
statements
else:
statements
25
25
if..elif..else statement
∙ The elif is short for else if and is useful to avoid excessive indentation
26
26
if..elif..else example
x=500
if x > 500 :
print(" X is greater than 500 ")
elif x < 500 :
print(" X is less than 500 ")
elif x == 500 :
print(" X is 500 ")
else :
print(" X is not a number ")
Output:
X is 500
∙ In the above case Python evaluates each expression one by one and if a True
condition is found the statement(s) block under that expression will be executed.
∙ If no true condition is found the statement(s) block under else will be executed.27
27
if… elif … else – Exercise 1
∙ Write a program that will ask a user to input the marks of a
student in the Programming module and display his grade, based
on the following criteria:
A+: 80 – 100
A: 70 – 79
B: 60 – 69
C: 50 – 59
D: 40 – 49
F: 0 – 39
28
28
Nested if statements
∙ In some situations you have to place an if statement inside
another statement
if condition:
if condition:
statements
else:
statements
else:
statements
29
29
Nested if example
mark = 72
if mark > 50:
if mark > = 80:
print ("You got A Grade !!")
elif mark > =60 and mark < 80 :
print ("You got B Grade !!")
else:
print ("You got C Grade !!")
else:
print("You failed!!")
Output
print ("You got B Grade !!")
30
30
Nested If- Exercise 2
mark = 100
if not (mark == 100):
print("mark is not 100")
else:
print("mark is 100")
33
and operator
mark = 72
if mark > 80:
print ("You got A Grade+ !!")
elif mark > =70 and mark < 80 :
print ("You got A Grade !!")
elif mark > =60 and mark < 70 :
print ("You got B Grade !!")
elif mark > =50 and mark < 60 :
print ("You got C Grade !!")
elif mark > =40 and mark < 50 :
print ("You got D Grade !!")
else:
print("You failed!!")
∙ Output
− You got A Grade !! 34
34
in operator
color = ['Red','Blue','Green'] #this is a list;
selColor = "Red"
if selColor in color:
print(selColor,"is in the list")
else:
print("Not in the list")
∙ Output
− Red is in the list
35
35
Exercise 3