0% found this document useful (0 votes)
17 views40 pages

04 Slide

Chapter 4 focuses on programming concepts related to Boolean expressions, comparison operators, and selection control statements in Python. It covers the implementation of one-way and two-way if statements, as well as nested conditions and logical operators. Additionally, it includes practical examples such as math quizzes and BMI calculations to illustrate these concepts.

Uploaded by

daviesikeoluwa7
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)
17 views40 pages

04 Slide

Chapter 4 focuses on programming concepts related to Boolean expressions, comparison operators, and selection control statements in Python. It covers the implementation of one-way and two-way if statements, as well as nested conditions and logical operators. Additionally, it includes practical examples such as math quizzes and BMI calculations to illustrate these concepts.

Uploaded by

daviesikeoluwa7
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/ 40

Chapter 4 Selections

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1


Motivations
If you assigned a negative value for radius in
Listing 2.1, ComputeArea.py, the program would
print an invalid result. If the radius is negative, you
don't want the program to compute the area. How
can you deal with this situation?

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


2
Objectives
 To write Boolean expressions by using comparison operators (§4.2).
 To generate random numbers by using the random.randint(a, b) or
random.random() functions (§4.3).
 To program with Boolean expressions (AdditionQuiz) (§4.3).
 To implement selection control by using one-way if statements (§4.4)
 To program with one-way if statements (GuessBirthday) (§4.5).
 To implement selection control by using two-way if .. else statements (§4.6).
 To implement selection control with nested if ... elif ... else statements (§4.7).
 To avoid common errors in if statements (§4.8).
 To program with selection statements (§4.9–4.10).
 To combine conditions by using logical operators (and, or, and not) (§4.11).
 To use selection statements with combined conditions (LeapYear, Lottery)
(§§4.12–4.13).
 To write expressions that use the conditional expressions (§4.14).
 To understand the rules governing operator precedence and associativity
(§4.15).
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 3
Boolean Data Types
Often in a program you need to compare two
values, such as whether i is greater than j. There
are six comparison operators (also known as
relational operators) that can be used to compare
two values. The result of the comparison is a
Boolean value: true or false.

b = (1 > 2)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


4
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
5
Problem: A Simple Math Learning Tool
This example creates a program to let a first grader
practice additions. The program randomly
generates two single-digit integers number1 and
number2 and displays a question such as “What is
7 + 9?” to the student. After the student types the
answer, the program displays a message to indicate
whether the answer is true or false.

AdditionQuiz Run

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


6
One-way if Statements
if radius >= 0:
if boolean-expression: area = radius * radius * 3.14159
statement(s)
print("The area for the circle of radius“,
radius, "is“, area)

False False
boolean-expression radius >= 0?

True True

Statement(s) area = radius * radius * 3.14159


print("The area for the circle of ",
"radius", radius, "is", area)

(a) (b)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


7
Note
if i > 0: if i > 0:
print("i is positive") print("i is positive")

(a) Wrong (b) Correct

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


8
Simple if Demo

Write a program that prompts the user to enter an integer. If the


number is a multiple of 5, print HiFive. If the number is divisible
by 2, print HiEven.

SimpleIfDemo Run

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


9
Problem: Guessing Birthday
The program can guess your birth date. Run
to see how it works.
= 19

1 3 5 7 2 3 6 7 4 5 6 7 8 9 10 11 16 17 18 19
9 11 13 15 10 11 14 15 12 13 14 15 12 13 14 15 20 21 22 23
17 19 21 23 18 19 22 23 20 21 22 23 24 25 26 27 24 25 26 27
25 27 29 31 26 27 30 31 28 29 30 31 28 29 30 31 28 29 30 31
Set1 Set2 Set3 Set4 Set5

GuessBirthday Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
10
Mathematics Basis for the Game
19 is 10011 in binary. 7 is 111 in binary. 23 is 11101 in binary
10000
10000 00110 1000
10 10 100
+ 1 + 1 + 1
10011 00111 11101

19 7 23

= 19

1 3 5 7 2 3 6 7 4 5 6 7 8 9 10 11 16 17 18 19
9 11 13 15 10 11 14 15 12 13 14 15 12 13 14 15 20 21 22 23
17 19 21 23 18 19 22 23 20 21 22 23 24 25 26 27 24 25 26 27
25 27 29 31 26 27 30 31 28 29 30 31 28 29 30 31 28 29 30 31
Set1 Set2 Set3 Set4 Set5
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
11
The Two-way if Statement
if boolean-expression:
statement(s)-for-the-true-case
else:
statement(s)-for-the-false-case

True False
boolean-expression

Statement(s) for the true case Statement(s) for the false case

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


12
if...else Example
if radius >= 0:
area = radius * radius * math.pi
print("The area for the circle of radius", radius, "is", area)
else:
print("Negative input")

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


13
Problem: An Improved Math Learning Tool
This example creates a program to teach a
first grade child how to learn subtractions.
The program randomly generates two single-
digit integers number1 and number2 with
number1 > number2 and displays a question
such as “What is 9 – 2?” to the student. After
the student types the answer in the input
dialog box, the program displays a message
dialog box to indicate whether the answer is
correct.
SubtractionQuiz Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
14
Multiple Alternative if Statements

if score >= 90.0: if score >= 90.0:


grade = 'A' grade = 'A'
else: elif score >= 80.0:
if score >= 80.0: Equivalent grade = 'B'
grade = 'B' elif score >= 70.0:
else: grade = 'C'
if score >= 70.0: elif score >= 60.0:
grade = 'C' grade = 'D'
else: else:
if score >= 60.0: This is better grade = 'F'
grade = 'D'
else:
grade = 'F'

(a) (b)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


15
Flowchart

False
score >= 90
False
True score >= 80
False
grade = 'A' True score >= 70
False
grade = 'B' True score >= 60

grade = 'C' True

grade = 'D'

grade = 'F'

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


16
animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if score >= 90.0:


grade = 'A'
elif score >= 80.0:
grade = 'B'
elif score >= 70.0:
grade = 'C'
elif score >= 60.0:
grade = 'D'
else:
grade = 'F'

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


17
animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if score >= 90.0:


grade = 'A'
elif score >= 80.0:
grade = 'B'
elif score >= 70.0:
grade = 'C'
elif score >= 60.0:
grade = 'D'
else:
grade = 'F'

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


18
animation
Trace if-else statement
Suppose score is 70.0 The condition is true

if score >= 90.0:


grade = 'A'
elif score >= 80.0:
grade = 'B'
elif score >= 70.0:
grade = 'C'
elif score >= 60.0:
grade = 'D'
else:
grade = 'F'

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


19
animation
Trace if-else statement
Suppose score is 70.0 grade is C

if score >= 90.0:


grade = 'A'
elif score >= 80.0:
grade = 'B'
elif score >= 70.0:
grade = 'C'
elif score >= 60.0:
grade = 'D'
else:
grade = 'F'

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


20
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if score >= 90.0:


grade = 'A'
elif score >= 80.0:
grade = 'B'
elif score >= 70.0:
grade = 'C'
elif score >= 60.0:
grade = 'D'
else:
grade = 'F'

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


21
Example
Now let us write a program to find out the Chinese Zodiac
sign for a given year. The Chinese Zodiac sign is based on
a 12-year cycle, each year being represented by an animal:
rat, ox, tiger, rabbit, dragon, snake, horse, sheep, monkey,
rooster, dog, and pig, in this cycle.

pig
0: monkey
rat
1: rooster
dog ox 2: dog
3: pig
rooster tiger 4: rat
year % 12 = 5: ox
monkey rabbit 6: tiger
7: rabbit ChineseZodiac
8: dragon
sheep dragon
9: snake
horse snake 10: horse
11: sheep
Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
22
Common Errors
Most common errors in selection statements
are caused by incorrect indentation. Consider
the following code in (a) and (b).
radius = -20 radius = -20

if radius >= 0: if radius >= 0:


area = radius * radius * 3.14 area = radius * radius * 3.14
print("The area is", area) print("The area is", area)
(a) Wrong (b) Correct

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


23
TIP

if number % 2 == 0: even = number % 2 == 0


Equivalent
even = True
else:
even = False This is shorter
(a) (b)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


24
Problem: Body Mass Index
Body Mass Index (BMI) is a measure of health on
weight. It can be calculated by taking your weight
in kilograms and dividing by the square of your
height in meters. The interpretation of BMI for
people 16 years or older is as follows:

BMI Interpretation

Below 18.5 Underweight


18.5-24.9 Normal ComputeBMI
25.0-29.9 Overweight
Above 30.0 Obese
Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
25
Problem: Computing Taxes
The US federal personal income tax is calculated
based on the filing status and taxable income.
There are four filing statuses: single filers, married
filing jointly, married filing separately, and head of
household. The tax rates for 2009 are shown below.
Married Filing
Marginal Married Filing
Single Jointly or Qualified Head of Household
Tax Rate Separately
Widow(er)
10% $0 – $8,350 $0 – $16,700 $0 – $8,350 $0 – $11,950

15% $8,351– $33,950 $16,701 – $67,900 $8,351 – $33,950 $11,951 – $45,500

25% $33,951 – $82,250 $67,901 – $137,050 $33,951 – $68,525 $45,501 – $117,450

28% $82,251 – $171,550 $137,051 – $208,850 $68,525 – $104,425 $117,451 – $190,200

33% $171,551 – $372,950 $208,851 – $372,950 $104,426 – $186,475 $190,201 - $372,950

35% $372,951+ $372,951+ $186,476+ $372,951+


© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
26
Problem: Computing Taxes, cont.
if status == 0:
# Compute tax for single filers
elif status == 1:
# Compute tax for married filing jointly
elif status == 2:
# Compute tax for married filing separately
elif status == 3:
# Compute tax for head of household
else:
# Display wrong status

ComputeTax Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
27
Logical Operators

Operator Description

not logical negation


and logical conjunction
or logical disjunction

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


28
Truth Table for Operator not
p not p Example (assume age = 24, gender = 'F')

True False not (age > 18) is False, because (age > 18) is True.
False True not (gender == 'M') is True, because (grade == 'M') is False.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


29
Truth Table for Operator and
p1 p2 p1 and p2 Example (assume age = 24, gender = 'F')

False False False (age > 18) and (gender == 'F') is True, because (age
False True False > 18) and (gender == 'F') are both True.

True False False (age > 18) and (gender != 'F') is False, because
(gender != 'F') is False.
True True True

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


30
Truth Table for Operator or
p1 p2 p1 or p2 Example (assume age = 24, gender = 'F')

False False False (age > 34) or (gender == 'F') is true, because (gender
False True True == 'F') is True.

True False True (age > 34) or (gender == 'M') is False, because (age >
True True True 34) and (gender == 'M') are both Talse.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


31
Examples
Here is a program that checks whether a number is divisible by 2
and 3, whether a number is divisible by 2 or 3, and whether a
number is divisible by 2 or 3 but not both:

TestBooleanOperators Run

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


32
Problem: Determining Leap Year?
This program first prompts the user to enter a year as
an int value and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by
100, or it is divisible by 400.
(year % 4 == 0 and year % 100 != 0) or (year % 400
== 0)

LeapYear Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
33
Problem: Lottery
Write a program that randomly generates a lottery of a two-
digit number, prompts the user to enter a two-digit number,
and determines whether the user wins according to the
following rule:
• If the user input matches the lottery in exact order, the
award is $10,000.
• If the user input matches the lottery, the award is
$3,000.
• If one digit in the user input matches a digit in the
lottery, the award is $1,000.

Lottery Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
34
Conditional Operator
if x > 0:
y=1
else:
y = -1

is equivalent to

y = 1 if x > 0 else -1

expression1 if boolean-expression else expression2

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


35
Conditional Operator
if num % 2 == 0:
print(str(num) + “is even”)
else:
print(str(num) + “is odd”);

print("number is even" if (number % 2 == 0)


else "number is odd")

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


36
Operator Precedence
 +, -
 **
 not
 *, /, //, %
 +, -
 <, <=, >, >=
 ==, !=
 and
 or
 =, +=, -=, *=, /=, //=, %= (Assignment operator)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


37
Operator Precedence and Associativity
The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the expression
in the inner parentheses is executed first.) When
evaluating an expression without parentheses, the
operators are applied according to the precedence rule and
the associativity rule.

If operators with the same precedence are next to each


other, their associativity determines the order of
evaluation. All binary operators except assignment
operators are left-associative.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


38
Operator Associativity
When two operators with the same precedence
are evaluated, the associativity of the operators
determines the order of evaluation. All binary
operators except assignment operators are left-
associative.
a – b + c – d is equivalent to ((a – b) + c) – d
Assignment operators are right-associative.
Therefore, the expression
a = b += c = 5 is equivalent to a = (b += (c = 5))

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.


39
Turtle: Location of an Object
Test whether a point is inside a circle. The program
prompts the user to enter the center of a circle, the
radius, and a point.

(x2, y2)

radius

(x1, y1)

PointInCircle Run
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
40

You might also like