0% found this document useful (0 votes)
16 views

04 Selection Structures

Uploaded by

micklanape
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)
16 views

04 Selection Structures

Uploaded by

micklanape
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
You are on page 1/ 42

Selection Structures

(if, if..else, if..elif..else)


Learning Outcomes
● Develop computer programs that incorporates selection
structures
○ if
○ if-else
○ if-elif-else
Recap[1]
∙ Variables - Used to store and retrieve data. Each has a value (which can be
undefined) and a type (partly hidden in Python)
∙ Simple types
− Number -- generally, what you'd consider an integer or a real number in
mathematics. For example: 17, -19, 17.19, 0, 2e3,…
− String -- a text.
● For example: "word"
● So called empty string, "", has no characters (its length is zero).
− Boolean -- truth values (True and False).
− NoneType -- the type of a special constant None that means "no value".
● This is not a zero (a number), nor an empty string, nor anything
else! None is different from any other constant and any other value
that a variable can get.
∙ Be careful: 17 is a number, while "17" is a string!
3

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

∙ What did just happen here?

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

∙ In Python, we can also use shorthands as follows:


− a < b < c as a shorthand for a < b and b < c
− and a < b > c as a shorthand for a < b and b > c
13

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.

∙ Selection is used for decisions, branching - choosing between 2 or


more alternative paths.
− if
− if...else
− if … elif … else

∙ Repetition used for looping, i.e. repeating a piece of code multiple


times in a row.
− for loop 18
− while loop
18
Python Control Structures[3]
∙ These control structures can be combined in computer
programming.
∙ E.g. A sequence may contain several loops; a loop may contain a
loop nested within it, or the two branches of a conditional
statement may each contain sequences with loops and more
conditionals.

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]

∙ A conditional is created with if statement


∙ There are two possible branches:
− the one that is executed if the condition is true,
− the one that is executed if the condition is false.
∙ However, sometimes, we want to say
− If condition1 is true, do job1,
− else if condition2 is true, do job2,
− else do job3

22

22
if statement

x=20
y=10
if x > y :
print(" X is bigger ")

∙ if statement evaluates the test expression.


− If test expression is evaluated to true (nonzero), statements
inside the body of if is executed.
− If test expression is evaluated to false (0), statements inside
the body of if is skipped. 23

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

• Consider the following problem. A student is asked to input his


marks. If his score is >= 70, he passes with Grade A. Else If his
score is below 70, but >= 40 he passes with Grade B. Else if his
score < 40 he fails with Grade F. Additionally there is another
check if the score is >=70.
If the score is above 80, the message “Excellent” gets
displayed. If the score is above 90, the message “Outstanding”
gets displayed.

Exercise: Write the pseudocode for the above problem to output


the Grade of the student depending on his marks and the message
“Excellent” or “Outstanding” if applicable. Convert the
Pseudocode to a Python program
Pseudocode
Input student marks
If mark >= 70
Then output Grade A
If mark >=90
Then output Outstanding
Else If mark>=80
Then output Excellent
Else if marks >=40
Then Output Grade B
Else
Output Grade F
not operator
∙ By using Not keyword we can change the meaning of the expressions, moreover we
can invert an expression.

mark = 100
if not (mark == 100):
print("mark is not 100")
else:
print("mark is 100")

∙ You can write same code using "!=" operator.


mark = 100
if (mark != 100):
print("mark is not 100")
else:
print("mark is 100") 33

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

• Write a program that asks the user his/her year of birth


and calculates his/her age, age. If he/she is below 18
years old, the program must display “You are a child
aged age years old!”. Otherwise, it must display “You are
an adult aged age years old!”.
Exercise 4

• A factory pays its workers at the rate of Rs 30 per hour if


the number of hours worked (per week) does not exceed
40. Otherwise, the hourly rate is Rs 50 for any hour
worked above 40 in a given week. Write a program that
calculates the weekly wages from number of hours
worked per week.
Exercise 5

• Write a program that reads an integer value, num, and


determines if it is a perfect square. If it is a perfect
square, then the program displays a message saying that
num is a perfect square.
• Note: A perfect square is a number whose square root is
an integer, e.g. 4 and 25 are perfect squares while 3 and 8
are not.
Exercise 6

• A year is a leap year if it is divisible by 4 unless it is a


century year (one that ends in 00) in which case it has to
be divisible by 400. Write a program to read in a year and
report whether it is a leap year or not.
Exercise 7

• Percentage marks attained by a student in three exams are


to be entered to a computer. An indication of Pass or Fail
is given out after the three marks are entered. The criteria
for passing are as follows: A student passes if all three
examinations are passed. Additionally a student may pass
if only one subject is failed and the overall average is
greater than or equal to 50. The pass mark for an
individual subject is 40. Write a program to implement
this task.
Exercise 8

• A speeding ticket fine policy is Rs 500 plus Rs 10 for


each km/hr over the speed limit of 90 km/hr.
• Write a program that accepts speed in km/hr as input, and
displays a message indicating that the speed limit has not
been exceeded or prints the amount of the fine that has to
be paid. Also, speed should be in the range of 0 – 300
km/hr. All speeds outside this range should be rejected as
invalid and a suitable message is to be displayed
Acknowledgments
● DGT1039Y lectures notes by Dr. Shakun Baichoo, FoICDT

You might also like