0% found this document useful (0 votes)
24 views111 pages

CF Chapter-008

Uploaded by

aliza
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)
24 views111 pages

CF Chapter-008

Uploaded by

aliza
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/ 111

Chapter No 8 : Selections

C E – 119
Computing Fundamentals (CF)

Compiled By:

Sir Syed University of Engineering & Technology


Engr.Syed Atir Iftikhar
Computer Engineering Department [email protected]
University Road, Karachi-75300, PAKISTAN 1
CE - 119 : Computing Fundamentals (CF)
 Course Objectives:
 This course covers the concepts and fundamentals
of computing and programming. Topics includes
history, components of computers, hardware,
software, operating systems, database, networks,
number systems and logic gates. Also it includes
programming topics such as basic building blocks,
loop, decision making statements.

2
CE - 119 : Computing Fundamentals (CF)
 Course Learning Outcomes ( CLO )
CLO Level
Outcome Statement
No. *
Explain the fundamental knowledge and concepts about
1 computing infrastructure including hardware, software, C2
database and networks.
Applying and Implementing number systems and logic
2 C3
gates.

Applying and Implementing problem solving skills and


3 C3
solve problems incorporating the concept of programming.
3
Books

 Text Books
1. Computing Essentials, Timothy O’Leary and Linda O’Leary

2. Introduction to Computers, Peter Norton, 6th Edition, McGraw-Hill

3. Introduction to Programming using Python, Daniel Liang

 Reference Books:
1. Discovering Computers, Misty Vermaat and Susan Sebok,
Cengage Learning

2. Using Information Technology: A Practical Introduction to Computers


& Communications, Williams Sawyer, 9th Edition, McGraw-Hill

3. Introduction to Python, Paul Deitel, Harvey Deitel


4
Marks Distribution

 Total Marks ( Theory ) ___________ 100


 Mid Term ___________ 30
 Assignments + Quizzes + Presentation ___________ 20
 Semester Final Examination Paper ___________ 50

 Total Marks ( Laboratory ) ___________ 50


 Lab File ___________ 15
 Subject Project ___________ 15
 Lab Exam/Quiz ( Theory Teacher ) ___________ 20

 https://sites.google.com/view/muzammil2050

5
Course Instructors

 Muzammil Ahmad Khan [email protected]


Assistant Professor, CED
Room No: BS-04

 Atir Iftikhar [email protected]


Lecturer, CED
Room No: BT-05

6
CE – 119: Computing Fundamentals Chapter

Selections

Compiled By:
Engr. Syed Atir Iftikhar [email protected]
7
Motivations

If you assigned a negative value for radius in computing the


area, 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?

8
Objectives
 To write Boolean expressions by using comparison operators
 To generate random numbers by using the random.randint(a, b) or
random.random() functions
 To program with Boolean expressions (AdditionQuiz)
 To implement selection control by using one-way if statements
 To program with one-way if statements (GuessBirthday)
 To implement selection control by using two-way if .. else statements
 To implement selection control with nested if ... elif ... else statements
 To avoid common errors in if statements
 To program with selection statements
 To combine conditions by using logical operators (and, or, and not)
 To use selection statements with combined conditions (LeapYear, Lottery)
 To write expressions that use the conditional expressions
 To understand the rules governing operator precedence and associativity9
Overview
 A program can decide which statements to execute based on
a condition. If you enter a negative value for radius for
calculating area of the circle, the program displays an invalid
result. If the radius is negative, the program cannot compute
the area. How can you deal with this situation?
 Like all high-level programming languages, Python provides
selection statements that let you choose actions with two or
more alternative courses. You can use the following selection
statement to overcome the problem.
10
Boolean Data Types
 A Boolean expression is an expression that evaluates to a
Boolean value True or False.
 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)
11
Relational / Comparison Operators

12
Comparison Operators
x=5
y=8 Output
print("x == y:", x == y) x == y: False
print("x != y:", x != y) x != y: True
print("x < y:", x < y) x < y: True
print("x > y:", x > y) x > y: False
print("x <= y:", x <= y) x <= y: True
print("x >= y:", x >= y) x >= y: False
13
Boolean Variable
 A variable that holds a Boolean value is known as a
Boolean variable.
 The Boolean data type is used to represent Boolean
values. A Boolean variable can hold one of the two
values: True or False.
 For example, the following statement assigns the value
True to the variable lightsOn:
lightsOn = True
 True and False are literals, just like a number such as 10.
They are reserved words and cannot be used as
identifiers in a program. Internally, Python uses 1 to
represent True and 0 for False.
14
Random Number
 The randint(a, b) function can be used to generate a
random integer between a and b, inclusively.
 Suppose you want to develop a program to help a first
grader practice addition. The program randomly
generates two single-digit integers, number1 and
number2, and displays to the student a question such as
What is 1 + 7,
 After the student types the answer, the program displays
a message to indicate whether it is true or false. To
generate a random number, you can use the randint(a, b)
function in the random module. This function returns a
random integer i between a and b, inclusively. To obtain
a random integer between 0 and 9, use randint(0, 9)
15
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.

16
Program 4.1
import random
# Generate random numbers
number1 = random.randint(0, 9)
number2 = random.randint(0, 9)
# Prompt the user to enter an answer
answer = eval(input("What is " +str(number1)+ " + " +
str(number2) + "? "))

# Display result
print(number1, "+", number2, "=", answer,
"is", number1 + number2 == answer)

17
Program 4.1
Output:
What is 1 + 5? 6
1 + 5 = 6 is True
 The program uses the randint function defined in the random
module. The import statement imports the module
 Python also provides another function, randrange(a, b),
for generating a random integer between a and b – 1, which is
equivalent to randint(a, b – 1). For example, randrange(0, 10)
and randint(0, 9) are the same. Since randint is more intuitive,
therefore generally randint is used.
 You can also use the random() function to generate a random
float r such that 0 <= r < 1.0.
18
if Statements

 Python has several types of selection statements:


 one-way if statements,
 two-way if-else statements,
 nested if statements,
 multi-way if-elif-else statements and
 conditional expressions

19
One-Way if Statement
 A one-way if statement executes an action if and only if the
condition is true.

 The syntax for a one-way if statement is:

if boolean-expression: statement(s)

# Note that the statement(s) must be indented

 The statement(s) must be indented at least one space to the


right of the if keyword and each statement must be indented
using the same number of spaces.
20
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)

A one-way
False False
boolean-expression radius >= 0? if statement
executes the
True True
statements if
Statement(s) area = radius * radius * 3.14159
print("The area for the circle of ", the condition
"radius", radius, "is", area)
is true.

(a) (b)
21
Note

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

(a) Wrong (b) Correct

 The statement(s) must be indented at least one space to the


right of the if keyword and each statement must be indented
using the same number of spaces.
 For consistency, we indent it four spaces.

22
Program 4.2
radius = eval(input("Enter the Radius: "))

if radius >= 4:

area = radius * radius * 3.14159

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

Error:

IndentationError: expected an indented block

23
Program 4.2
radius = eval(input("Enter the Radius: "))

if radius >= 4:

area = radius * radius * 3.14159

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

24
Program 4.2
Output:
Enter the Radius: 5
The area for the circle of radius 5 is 78.53975

Enter the Radius: 3


NameError: name 'area' is not defined

25
Simple if Demo
Write a program that prompts the user to enter an
integer. If the number is a multiple of 5, print Hi-Five.
If the number is divisible by 2, print Hi-Even.

26
Program 4.3 Hi_Five.py

number = eval(input("Enter an integer: "))

if number % 5 == 0:

print("Hi-Five")

if number % 2 == 0:

print("Hi-Even")

27
Program 4.3 Hi_Five.py

Output:
Enter an integer: 5
Hi-Five

Enter an integer: 6
Hi-Even

Enter an integer: 10
Hi-Five
Hi-Even
28
Problem: Guessing Birthday
 You can find out the date of the month when your friend was
born by asking five questions.
 Each question asks whether the day is in one of the five sets of
numbers. The birthday is the sum of the first numbers in the
sets where the date appears.
 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

29
Problem: Guessing Birthday
 The birthday is the sum of the first numbers in the sets where
the date appears.

 For example, if the birthday is 19, it appears in Set1, Set2, and


Set5. The first numbers in these three sets are 1, 2, and 16.
Their sum is 19. = 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

30
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
31
Program 4.4 Guessing_Birthday.py
day = 0 # birth day to be determined

# Prompt the user to answer the first question

question1 = "Is your birthday in Set1?\n" + \

" 1 3 5 7\n" + \

" 9 11 13 15\n" + \

"17 19 21 23\n" + \

"25 27 29 31" + \

"\nEnter 0 for No and 1 for Yes: "

answer = eval(input(question1))

if answer == 1:

day += 1
32
Program 4.4 Guessing_Birthday.py
# Prompt the user to answer the second question

question2 = "Is your birthday in Set2?\n" + \

" 2 3 6 7\n" + \

"10 11 14 15\n" + \

"18 19 22 23\n" + \

"26 27 30 31" + \

"\nEnter 0 for No and 1 for Yes: "

answer = eval(input(question2))

if answer == 1:

day += 2
33
Program 4.4 Guessing_Birthday.py
# Prompt the user to answer the third question

question3 = "Is your birthday in Set3?\n" + \

" 4 5 6 7\n" + \

"12 13 14 15\n" + \

"20 21 22 23\n" + \

"28 29 30 31" + \

"\nEnter 0 for No and 1 for Yes: "

answer = eval(input(question3))

if answer == 1:

day += 4
34
Program 4.4 Guessing_Birthday.py
# Prompt the user to answer the fourth question

question4 = "Is your birthday in Set4?\n" + \

" 8 9 10 11\n" + \

"12 13 14 15\n" + \

"24 25 26 27\n" + \

"28 29 30 31" + \

"\nEnter 0 for No and 1 for Yes: "

answer = eval(input(question4))

if answer == 1:

day += 8
35
Program 4.4 Guessing_Birthday.py
# Prompt the user to answer the fifth question

question5 = "Is your birthday in Set5?\n" + \

"16 17 18 19\n" + \

"20 21 22 23\n" + \

"24 25 26 27\n" + \

"28 29 30 31" + \

"\nEnter 0 for No and 1 for Yes: "

answer = eval(input(question5))

if answer == 1:

day += 16

print("\nYour birthday is: " + str(day) )


36
Program 4.4 Guessing_Birthday.py

Output:
Is your birthday in Set1?
1 3 5 7
9 11 13 15
17 19 21 23
25 27 29 31
Enter 0 for No and 1 for Yes: 0

37
Program 4.4 Guessing_Birthday.py

Output:
Is your birthday in Set2?
2 3 6 7
10 11 14 15
18 19 22 23
26 27 30 31
Enter 0 for No and 1 for Yes: 1

38
Program 4.4 Guessing_Birthday.py

Output:
Is your birthday in Set3?
4 5 6 7
12 13 14 15
20 21 22 23
28 29 30 31
Enter 0 for No and 1 for Yes: 0

39
Program 4.4 Guessing_Birthday.py

Output:
Is your birthday in Set4?
8 9 10 11
12 13 14 15
24 25 26 27
28 29 30 31
Enter 0 for No and 1 for Yes: 1

40
Program 4.4 Guessing_Birthday.py

Output:
Is your birthday in Set5?
16 17 18 19
20 21 22 23
24 25 26 27
28 29 30 31
Enter 0 for No and 1 for Yes: 0

Your birthday is: 10


>>>
41
Program 4.4 Guessing_Birthday.py

42
The Two-way if Statement
 A two-way if-else statement decides which
statements to execute based on whether the condition
is true or false.
 A one-way if statement takes an action if the
specified condition is True. If the condition is False,
nothing is done. But what if you want to take one or
more alternative actions when the condition is False?
 You can use a two-way if-else statement. The actions
that a two-way if-else statement specifies differ based
on whether the condition is True or False
43
The Two-way if Statement
if boolean-expression:
statement(s)-for-the-true-case
else:
statement(s)-for-the-false-case

44
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")

45
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.

46
Problem: An Improved Math Learning Tool
 The program may work as follows:
 Step 1: Generate two single-digit integers for number1
and number2.
 Step 2: If number1 < number2, swap number1 with
number2.
 Step 3: Prompt the student to answer,
“What is number1 – number2?”
 Step 4: Check the student’s answer and display whether
the answer is correct

47
Program 4.5
import random

# 1. Generate two random single-digit integers

number1 = random.randint(0, 9)

number2 = random.randint(0, 9)

# 2. If number1 < number2, swap number1 with number2

if number1 < number2:

number1, number2 = number2, number1 # Simultaneous assignment

48
Program 4.5
# 4. Prompt the student to answer "what is number1 - number2?"

answer = eval(input("What is " + str(number1) + " - " +

str(number2) + "? "))

# 4. Grade the answer and display the result

if number1 - number2 == answer:

print("You are correct!")

else:

print("Your answer is wrong.\n", number1, "-",

number2, "is", number1 - number2)

49
Program 4.5
Output:
What is 3 - 1? 2
You are correct!

What is 8 - 5? 1
Your answer is wrong.
8 - 5 is 3

50
Nested if
 One if statement can be placed inside another
if statement to form a nested if statement.

if i > k:
if j > k:
print("i and j are greater than k")
else:
print("i is less than or equal to k")
51
Nested if
 The statement in an if or if-else statement can be
any legal Python statement, including another if or
if-else statement.

 The inner if statement is said to be nested inside the


outer if statement. The inner if statement can
contain another if statement; in fact, there is no
limit to the depth of the nesting.

52
Multiple Alternative (MultiWay)
if Statements

53
Flowchart

54
Multiway if Statements

 This style, called multiway if statements, avoids


deep indentation and makes the program easier to
read.

 The multi-way if statements uses the syntax


if-elif-else; elif (short for else if ) is a Python
keyword.

55
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'

56
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'

57
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'

58
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'

59
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'

60
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
8: dragon
sheep dragon
9: snake
horse snake 10: horse
11: sheep
61
Program 4.6 Chinese_Zodiac_Sign.py

year = eval(input("Enter a year: "))

zodiacYear = year % 12

if zodiacYear == 0:

print("monkey")

elif zodiacYear == 1:

print("rooster")

elif zodiacYear == 2:

print("dog")

62
Program 4.6 Chinese_Zodiac_Sign.py

elif zodiacYear == 3:

print("pig")

elif zodiacYear == 4:

print("rat")

elif zodiacYear == 5:

print("ox")

elif zodiacYear == 6:

print("tiger")

63
Program 4.6 Chinese_Zodiac_Sign.py
elif zodiacYear == 7:

print("rabbit")

elif zodiacYear == 8:

print("dragon")

elif zodiacYear == 9:

print("snake")

elif zodiacYear == 10:

print("horse")

else:

print("sheep")
64
Program 4.6 Chinese_Zodiac_Sign.py

Output:
Enter a year: 2021
ox

Enter a year: 1950


tiger

Enter a year: 20
dragon

65
66
Common Errors
Most common errors in selection statements are
caused by incorrect indentation. Consider the
following code in (a) and (b).

67
Common Errors
 In (a), the print statement is not in the if block.
 To place it in the if block, you have to indent it,
as shown in (b).

68
Common Errors in Nested If
 Consider another example in the following code in (a) and (b).
The code in (a) below has two if clauses and one else clause.
 Which if clause is matched by the else clause?
 The indentation indicates that the else clause matches the first
if clause in (a) and the second if clause in (b).

69
Common Errors

 TIP: The code can be simplified by assigning


the test value directly to the variable, as
shown in (b)
70
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:
Formula: weight (kg) / [height (m)]2

71
Program 4.7 Body_Mass_Index.py

# Prompt the user to enter weight in pounds

weight = eval(input("Enter weight in pounds: "))

# Prompt the user to enter height in inches

height = eval(input("Enter height in inches: "))

KILOGRAMS_PER_POUND = 0.45359237 # Constant

METERS_PER_INCH = 0.0254 # Constant

72
Program 4.7 Body_Mass_Index.py

# Compute BMI

weightInKilograms = weight * KILOGRAMS_PER_POUND

heightInMeters = height * METERS_PER_INCH

bmi = weightInKilograms / (heightInMeters * heightInMeters)

73
Program 4.7 Body_Mass_Index.py

# Display result

print("BMI is", format(bmi, ".2f"))

if bmi < 18.5:

print("Underweight")

elif bmi < 25:

print("Normal")

elif bmi < 30:

print("Overweight")

else:

print("Obese")
74
Program 4.7 Body_Mass_Index.py

Output:
Enter weight in pounds: 146
Enter height in inches: 70
BMI is 20.95
Normal

Enter weight in pounds: 120


Enter height in inches: 70
BMI is 17.22
Underweight
75
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.
If you are, say, single with a taxable income of $10,000, the first
$8,350 is taxed at 10% and the other $1,650 is taxed at 15%.
So, your tax is $1,082.50.
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+


76
Problem: Computing Taxes
 You are to write a program to compute personal income tax.
Your program should prompt the user to enter the filing status
and taxable income and then compute the tax. Enter 0 for
single filers, 1 for married filing jointly, 2 for married filing
separately, and 3 for head of household.

77
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
78
Boolean or Logical Operators
 The logical operators not, and, and or can be used to create a
composite condition. Sometimes, a combination of several
conditions determines whether a statement is executed. You
can use logical operators to combine these conditions to
form a compound expression.

 Logical operators, also known as Boolean operators, operate


on Boolean values to create a new Boolean value.
 The not operator, which negates True to False and False
to True.
 The and of two Boolean operands is true if and only if
both operands are true.
 The or of two Boolean operands is true if at least one of
the operands is true.
79
Boolean or Logical Operators

80
Truth Table for Operator not

81
Truth Table for Operator and

82
Truth Table for Operator or

83
Boolean/Logical Expressions
a=6
b=7 Output
c = 42
1 True
print(1, a == 6)
2 False
print(2, a == 7)
3 True
print(3, a == 6 and b == 7)
4 False
print(4, a == 7 and b == 7)
5 True
print(5, not a == 7 and b == 7)
6 True
print(6, a == 7 or b == 7)
7 False
print(7, a == 7 or b == 6)
8 True
print(8, not (a == 7 and b == 6))
9 False
print(9, not a == 7 and b ==846)
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:

85
Program 4.8 Number_Divisible.py

# Receive an input

number = eval(input("Enter an integer: "))

if number % 2 == 0 and number % 3 == 0:

print(number, "is divisible by 2 and 3")

if number % 2 == 0 or number % 3 == 0:

print(number, "is divisible by 2 or 3")

if (number % 2 == 0 or number % 3 == 0) and \

not (number % 2 == 0 and number % 3 == 0):

print(number, "divisible by 2 or 3, but not both")

86
Program 4.8 Number_Divisible.py

Output:
Enter an integer: 18
18 is divisible by 2 and 3
18 is divisible by 2 or 3

Enter an integer: 15
15 is divisible by 2 or 3
15 divisible by 2 or 3, but not both

87
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)

88
Program 4.9 Leap_Year.py

year = eval(input("Enter a year: "))

# Check if the year is a leap year

isLeapYear = (year % 4 == 0 and year % 100 != 0) or \ (year % 400 == 0)

# Display the result

print(year, "is a leap year?", isLeapYear)

89
Program 4.9 Leap_Year.py

Output:
Enter a year: 2010
2010 is a leap year? False

Enter a year: 2000


2000 is a leap year? True

90
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 in any order,
the award is $3,000.
 If one digit in the user input matches a digit in the
lottery, the award is $1,000.

91
Program 4.10 Lottery.py

import random

# Generate a lottery

lottery = random.randint(0, 99)

# Prompt the user to enter a guess

guess = eval(input("Enter your lottery pick (two digits): "))

# Get digits from lottery

lotteryDigit1 = lottery // 10

lotteryDigit2 = lottery % 10

92
Program 4.10 Lottery.py

# Get digits from guess

guessDigit1 = guess // 10

guessDigit2 = guess % 10

print("The lottery number is", lottery)

93
Program 4.10 Lottery.py
# Check the guess
if guess == lottery:
print("Exact match: you win $10,000")
elif (guessDigit2 == lotteryDigit1 and \
guessDigit1 == lotteryDigit2):
print("Match all digits: you win $3,000")
elif (guessDigit1 == lotteryDigit1
or guessDigit1 == lotteryDigit2
or guessDigit2 == lotteryDigit1
or guessDigit2 == lotteryDigit2):
print("Match one digit: you win $1,000")
else:
print("Sorry, no match")
94
Program 4.10 Lottery.py

Output:
Enter your lottery pick (two digits): 45
The lottery number is 94
Match one digit: you win $1,000

Enter your lottery pick (two digits): 23


The lottery number is 3
Match one digit: you win $1,000

Enter your lottery pick (two digits): 10


The lottery number is 94
Sorry, no match 95
Conditional Operator
if x > 0:
y=1
else:
y = -1

is equivalent to

y = 1 if x > 0 else -1

 Conditional expressions are in a completely different style.


The syntax is:
expression1 if boolean-expression else expression2
96
Conditional Operator
 Conditional expressions are in a completely different style.
The syntax is:

expression1 if boolean-expression else expression2


 The result of this conditional expression is expression1 if
boolean-expression is true; otherwise, the result is expression2.
Suppose you want to assign the larger number of variables
number1 and number2 to max. You can simply write a statement
using the conditional expression:

max = number1 if number1 > number2 else number2


97
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")

98
Operator Precedence
 Operator precedence and associativity determine the order in
which operators are evaluated.

 Operator precedence and operator associativity determine the


order in which Python evaluates operators.

 Suppose that you have this expression:

3 + 4 * 4 > 5 * (4 + 3) – 1

 What is its value?

 What is the execution order of the operators?


99
Operator Precedence

100
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.
101
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))
102
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.

103
Turtle: Location of an Object
 Detecting the Location of an Object Detecting whether an
object is inside another object is a common task in game
programming.
 In game programming, often you need to determine whether
an object is inside another object. This section gives an
example of testing whether a point is inside a circle.
The program prompts the user to enter the center of a circle,
the radius, and a point.
 The program then displays the circle and the point along with
a message indicating whether the point is inside or outside the
circle 104
Program 4.11 Location_of_an_object.py
import turtle

x1, y1 = eval(input("Enter the center of a circle x, y: "))

radius = eval(input("Enter the radius of the circle: "))

x2, y2 = eval(input("Enter a point x, y: "))

# Draw the circle

turtle.penup() # Pull the pen up

turtle.goto(x1, y1 - radius)

turtle.pendown() # Pull the pen down

turtle.circle(radius)
105
Program 4.11 Location_of_an_object.py
# Draw the point

turtle.penup() # Pull the pen up

turtle.goto(x2, y2)

turtle.pendown() # Pull the pen down

turtle.begin_fill() # Begin to fill color in a shape

turtle.color("red")

turtle.circle(3)

turtle.end_fill() # Fill the shape

106
Program 4.11 Location_of_an_object.py
# Display the status

turtle.penup() # Pull the pen up

turtle.goto(x1 - 70, y1 - radius - 20)

turtle.pendown()

d = ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) ** 0.5

if d <= radius:

turtle.write("The point is inside the circle")

else:

turtle.write("The point is outside the circle")

turtle.hideturtle()

turtle.done()
107
Program 4.11 Location_of_an_object.py

Output:
Enter the center of a circle x, y: 10,20
Enter the radius of the circle: 50
Enter a point x, y: 10,20

108
Program 4.11 Location_of_an_object.py

Output:
Enter the center of a circle x, y: 10,10
Enter the radius of the circle: 50
Enter a point x, y: 60,70

109
110
111

You might also like