CF Chapter-008
CF Chapter-008
C E – 119
Computing Fundamentals (CF)
Compiled By:
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.
Text Books
1. Computing Essentials, Timothy O’Leary and Linda O’Leary
Reference Books:
1. Discovering Computers, Misty Vermaat and Susan Sebok,
Cengage Learning
https://sites.google.com/view/muzammil2050
5
Course Instructors
6
CE – 119: Computing Fundamentals Chapter
Selections
Compiled By:
Engr. Syed Atir Iftikhar [email protected]
7
Motivations
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
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
19
One-Way if Statement
A one-way if statement executes an action if and only if the
condition is true.
if boolean-expression: statement(s)
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")
22
Program 4.2
radius = eval(input("Enter the Radius: "))
if radius >= 4:
print("The area for the circle of ", "radius", radius, "is", area)
Error:
23
Program 4.2
radius = eval(input("Enter the Radius: "))
if radius >= 4:
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
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
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.
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
" 1 3 5 7\n" + \
" 9 11 13 15\n" + \
"17 19 21 23\n" + \
"25 27 29 31" + \
answer = eval(input(question1))
if answer == 1:
day += 1
32
Program 4.4 Guessing_Birthday.py
# Prompt the user to answer the second question
" 2 3 6 7\n" + \
"10 11 14 15\n" + \
"18 19 22 23\n" + \
"26 27 30 31" + \
answer = eval(input(question2))
if answer == 1:
day += 2
33
Program 4.4 Guessing_Birthday.py
# Prompt the user to answer the third question
" 4 5 6 7\n" + \
"12 13 14 15\n" + \
"20 21 22 23\n" + \
"28 29 30 31" + \
answer = eval(input(question3))
if answer == 1:
day += 4
34
Program 4.4 Guessing_Birthday.py
# Prompt the user to answer the fourth question
" 8 9 10 11\n" + \
"12 13 14 15\n" + \
"24 25 26 27\n" + \
"28 29 30 31" + \
answer = eval(input(question4))
if answer == 1:
day += 8
35
Program 4.4 Guessing_Birthday.py
# Prompt the user to answer the fifth question
"16 17 18 19\n" + \
"20 21 22 23\n" + \
"24 25 26 27\n" + \
"28 29 30 31" + \
answer = eval(input(question5))
if answer == 1:
day += 16
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
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:
else:
print("Negative input")
45
Problem: An Improved Math Learning Tool
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
number1 = random.randint(0, 9)
number2 = random.randint(0, 9)
48
Program 4.5
# 4. Prompt the student to answer "what is number1 - number2?"
else:
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.
52
Multiple Alternative (MultiWay)
if Statements
53
Flowchart
54
Multiway if Statements
55
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
56
animation
Trace if-else statement
57
animation
Trace if-else statement
Suppose score is 70.0 The condition is true
58
animation
Trace if-else statement
59
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement
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
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")
print("horse")
else:
print("sheep")
64
Program 4.6 Chinese_Zodiac_Sign.py
Output:
Enter a year: 2021
ox
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
71
Program 4.7 Body_Mass_Index.py
72
Program 4.7 Body_Mass_Index.py
# Compute BMI
73
Program 4.7 Body_Mass_Index.py
# Display result
print("Underweight")
print("Normal")
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
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.
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
85
Program 4.8 Number_Divisible.py
# Receive an input
if number % 2 == 0 or number % 3 == 0:
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?
88
Program 4.9 Leap_Year.py
89
Program 4.9 Leap_Year.py
Output:
Enter a year: 2010
2010 is a leap year? False
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:
91
Program 4.10 Lottery.py
import random
# Generate a lottery
lotteryDigit1 = lottery // 10
lotteryDigit2 = lottery % 10
92
Program 4.10 Lottery.py
guessDigit1 = guess // 10
guessDigit2 = guess % 10
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
is equivalent to
y = 1 if x > 0 else -1
if num % 2 == 0:
print(str(num) + “is even”)
else:
print(str(num) + “is odd”);
98
Operator Precedence
Operator precedence and associativity determine the order in
which operators are evaluated.
3 + 4 * 4 > 5 * (4 + 3) – 1
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
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
turtle.goto(x1, y1 - radius)
turtle.circle(radius)
105
Program 4.11 Location_of_an_object.py
# Draw the point
turtle.goto(x2, y2)
turtle.color("red")
turtle.circle(3)
106
Program 4.11 Location_of_an_object.py
# Display the status
turtle.pendown()
if d <= radius:
else:
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