0% found this document useful (0 votes)
7 views31 pages

MA1008 Week 4 (Program Control - Decisions and Branching)

The document covers various topics related to computational thinking and programming in Python, including control structures, boolean expressions, and error handling. It includes tutorial questions and hands-on exercises that require students to write Python code for different scenarios, such as determining pay, comparing birthdays, and checking leap years. The document emphasizes understanding the problem, inputs, outputs, and logical flow in programming.

Uploaded by

Ananya Jayanty
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)
7 views31 pages

MA1008 Week 4 (Program Control - Decisions and Branching)

The document covers various topics related to computational thinking and programming in Python, including control structures, boolean expressions, and error handling. It includes tutorial questions and hands-on exercises that require students to write Python code for different scenarios, such as determining pay, comparing birthdays, and checking leap years. The document emphasizes understanding the problem, inputs, outputs, and logical flow in programming.

Uploaded by

Ananya Jayanty
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/ 31

Introduction to Computational Thinking

MA1008
Program Control
Decisions and Branching
Week 4
Week 4_Tutorial_Question 1
What is printed in the following statements?
times = 5
print ("## "*times)

Ans: ## ## ## ## ##

*Note that there is a space character after the 5th ##


Week 4_Tutorial_Question 2
Assuming that x = 11, y = 6, z = 2, c = 'a', d = ' z ', what are the values of the expressions in the
following table?
a) x == 5 or y != 3 True
b) not (x > 9 and y != 23) False
c) x <= 1 and y == 6 or z < 4 True (“and” has higher priority than “or”)
d) 5 and y !=8 or 0 True
e) x >= y >= z True
f) c >= 'A' or d >= 'Z' True
g) c <= 'e' <= d True
h) c <= 2 <= d Error
i) c == 'a' or 'e' or 'i' or 'o' or 'u' True
j) d == 'a' or 'e' or 'i' or 'o' or 'u' True
Can the code in i) and j) be used for vowel test?
Boolean Algebra Truth Tables
“A” and “B” are inputs. “Y” is the output.
Letters have numeric values as specified by ASCII standard
Week 4_Tutorial_Question 2
Assuming that x = 11, y = 6, z = 2, c = 'a', d = 'z' , what are the values of the expressions in the
following table?

a) x == 5 or y != 3 b) not (x > 9 and y != 23)

not (True and True)


(x == 5) or (y != 3)
not (True) returns a value of False
False or True returns a value of True
Week 4_Tutorial_Question 2
Assuming that x = 11, y = 6, z = 2, c = 'a', d = 'z', what are the values of the expressions in the
following table?

c) x <= 1 and y == 6 or z < 4 d) 5 and y !=8 or 0

(x <= 1 and y == 6) or (z < 4) (5 and y !=8) or 0

(False and True) or True (True and True) or False


returns a value of True
False or True returns a value of True
Week 4_Tutorial_Question 2
Assuming that x = 11, y = 6, z = 2, c = 'a', d = 'z', what are the values of the expressions in the
following table?

e) x >= y >= z f) c >= 'A' or d >= 'Z'

(x >= y and y >= z) (c >= 'A') or (d >= 'Z')

(97Ascii >= 65Ascii) or (121Ascii


(True and True)
>= 90Ascii)
returns a value of True
True or True returns a value of True
Week 4_Tutorial_Question 2
Assuming that x = 11, y = 6, z = 2, c = 'a', d = 'z', what are the values of the expressions in the
following table?

g) c <= 'e' <= d h) c <= 2 <= d

(97Ascii <= 2) or (2 <= 121Ascii)


(97Ascii <= 101Ascii) and (101Ascii
<= 121Ascii)
Type Error!
TypeError: '<=' not supported between instances of
'str' and 'int'
(True and True)
returns a value of True
Week 4_Tutorial_Question 2
Assuming that x = 11, y = 6, z = 2, c = 'a', d = 'z', what are the values of the expressions in the
following table?
i) c == 'a' or 'e' or 'i' or 'o' or 'u'
(c == 'a') or ('e') or ('i') or ('o') or ('u')
(97Ascii == 97Ascii) or (True) or (True) or (True) or (True)
(True) or (True) or (True) or (True) or (True) returns a value of True

j) d == 'a' or 'e' or 'i' or 'o' or 'u'


(d == 'a') or ('e') or ('i') or ('o') or ('u')
(121Ascii == 97Ascii) or (True) or (True) or (True) or (True)
(False) or (True) or (True) or (True) or (True)returns a value of True
Actually, in the above statement that has only the "or" comparison, the program stops evaluating the rest of
the Booleans after 'e' because the first True is sufficient.

For parts i and j, remember that non-empty strings, lists, tuples and dictionaries are considered “True”.
Week 4_Tutorial_Question 3
The code below determines if a given number is small, medium, large or out of range. Correct
any error that might exist. After the correction, what is printed if you input 7?
num1 = input ("Enter a positive integer: ")
Hint:
if num1< 5 A quick examination of this
if num1 <= 0 code suggests that any
positive number between 0
print num1 ("is out of range") (excluding zero) and 5
(excluding 5) is a small value.
else
print num1; (" is a small value.") Any positive number above 5
is a large value.
elseif num1 = 5
print num1; ("is a medium value. ") 5 is a medium value.
else #num1 > 5
print num1; ("This is a large value. ")
Week 4_Tutorial_Question 3
The code below determines if a given number is small, medium, large or out of range. Correct
any error that might exist. After the correction, what is printed if you input 7?
num1 = int( input ("Enter a positive integer: "))
if num1< 5:
if num1 <= 0:
print (num1, "is out of range")
else:
print ( num1, " is a small value.")
elif num1 == 5:
print ( num1, "is a medium value. ")
else: #num1 > 5
print ( num1, "This is a large value. ")
Week 4_Tutorial_Question 4
What is the difference in the logic of the following two sets of code:
(i) if BooleanA:
Suite A
if BooleanB:
Suite B
(ii) if BooleanA:
Suite A
elif BooleanB:
Suite B
In the first set, the checking of BooleanB and execution of Suite B are independent of BooleanA, whereas in the
second set, they are executed only upon BooleanA being False.
Week 4_Tutorial_Question 5
Write a program that prints the largest of three numbers.
This is a repeat of a question in the previous tutorial. But now the students have to deliver the solution
in Python. Assume that the three numbers are stored in variables A, B and C. (Students should use the
input() function to read in the three variables.)

A = int(input("Enter value of A: ")


B = int(input("Enter value of B: ")
C = int(input("Enter value of C: ")
biggest = A
if (B > biggest):
biggest = B
if (C > biggest):
biggest = C
print(biggest)
Week 4_Tutorial_Question 6
You are writing a Python program to determine if an applicant qualifies for admission into
NTU. The selection uses two criteria: academic result and aptitude test. The academic result is
a score in the range 0-100 and the aptitude test is awarded one of these letter grades: A, B, C,
D and E. A candidate who satisfies one of the following two criteria qualifies:
• Academic score greater than or equal to 75 with aptitude grade of A, B, or C
• Academic score greater than or equal to 60 with aptitude grade of A only.
Your program stores the academic score in an integer variable called S and the aptitude grade
in a string variable called G. Write a Boolean expression in one line that returns True if an
applicant qualifies based on the above criteria and False otherwise. (Do not write multiple
statements.)

• Ans: (S >= 75 and G in "ABC") or (S >= 60 and G=="A")


• Note that G in "ABC" may be written as (G=="A" or G=="B" or G=="C")
Hands On Session
The purpose of this lab is for you to practise using the Python programming environment
and do some basic programming with Python. Before you start, you are advised to review
the material in the lectures to pick up the related basic elements in Python such as
comments, keywords, variables, operators, etc.

In this exercise, you are to devise Python programs to solve simple problems. But before you
start the coding on each problem, you are strongly advised to think about the followings:

1) What is the problem here? Understand and analyze it first.


2) What are the input(s) and output(s)?
3) Do I need to use any formulae?
4) What are the steps in the program?

After that, you can first build a simple skeleton for each major steps using simple English. That
is, write the pseudo-code.
Week 4_Hands-On_Question 1
Write a Python program that requests the number of hours one worked in a month and then
prints out the gross pay, taxes, and net pay. Assume that the pay structure and tax rate are as
follows:
• Basic pay rate = $10.00 per hour
• Overtime (>160 hours) = one and a half time of the basic pay rate
• Tax rate = 10% for first $1000, 20% for next $500, and 30% for the rest
Week 4_Hands-On_Question 1
basic_pay = 10.0
hours = float(input("Enter hours worked: "))

# Calculate pay
if (hours <= 160):
pay = hours*basic_pay
else:
pay = 160*basic_pay + (hours-160)*basic_pay*1.5

# Calculate tax
if (pay <= 1000):
tax = pay*0.1
elif (pay <= 1500): # 100 is tax for first $1000
tax = 100 + (pay-1000)*0.2
else: # pay > 1500, 200 is tax for first 1500.
tax = 200 + (pay-1500)*0.3

print("Gross pay = $", pay, "and tax = $", tax)


Week 4_Hands-On_Question 2
Write a Python program that reads 3 integers, say a, b, and c, and then computes and reports
the numerical range covered by them. Note that numerical range is defined as the difference
between the largest and the smallest values among the 3 numbers.
n1 = float(input("Enter 1st number: "))
n2 = float(input("Enter 2nd number: "))
n3 = float(input("Enter 3rd number: "))

#find the biggest number


biggest = n1
if (n2 > biggest):
biggest = n2
# find the smallest number
if (n3 > biggest):
smallest = n1
biggest = n3
if (n2 < smallest):
smallest = n2
if (n3 < smallest):
smallest = n3

range = biggest - smallest


print("The range of", n1, ",", n2, ", and", n3, "is", range)
Week 4_Hands-On_Question 3
Write a Python program to first read 3 integers representing a person’s birthday (day, month
and year) followed by another 3 integers representing another person’s birthday. Then, your
program has to compare the integers, and report who is older, or whether they have the same
birthday.
In this question, you cannot use any operators including and, or, and not, as well as
mathematical operators including multiplication (*) and addition (+). But you can use
relational operators for comparison.
Week 4_Hands-On_Question 3

# Get inputs
print("please input birthday of 1st person" )
y1 = int( input( " year: " ) )
m1 = int( input( " month: " ) )
d1 = int( input( " day: " ) )
print("please input birthday of 2nd person" )
y2 = int( input( " year: " ) )
m2 = int( input( " month: " ) )
d2 = int( input( " day: " ) )
Week 4_Hands-On_Question 3
# compare the integers
if y1 < y2:
print( "person 1 is older" )
elif y2 < y1:
print( "person 2 is older" )
else: #the program flows into this portion only if y1 is the same as y2
if m1 < m2:
print( "person 1 is older" )
elif m2 < m1:
print( "person 2 is older" )
else: #the program flows into this portion only if m1 is the same as m2
if d1 < d2:
print( "person 1 is older" )
elif d2 < d1:
print( "person 2 is older" )
else:
print( "they have the same birthday" )
Week 4_Hands-On_Question 4
A year is a leap year if it is divisible by 4 and not by 100, or if it is divisible by 400. Otherwise, it
is not a leap year. Write a program that reads in an integer value and returns true if the value
represents a leap year and false otherwise.

year = int(input("Enter the year: "))

if ((year%4==0) and not (year%100==0)) or (year%400==0):


print(year, "is a leap year")
else:
print(year, "is not a leap year")
Week 4_Hands-On_Question 5
Write a program that reads in a number between 1 and 7 and prints “Monday” for 1,
“Tuesday” for 2, …, “Sunday” for 7, and “Illegal input” if the number is out of range.
day = int(input("Enter an integer: "))

if (day == 1):
print("Monday")
elif (day == 2):
print("Tuesday")
elif (day == 3):
print("Wednesday")
elif (day == 4):
print("Thursday")
elif (day == 5):
print("Friday")
elif (day == 6):
print("Saturday")
elif (day == 7):
print("Sunday")
else:
print("Illegal input")
Week 4_Hands-On_Question 6
Write a program that reads in the coefficients of a quadratic equation and prints the roots
when real roots exist and the message “No real roots” otherwise.
Hints
We begin addressing this question by thinking about the following:
1) Asking the user to input the coefficients of a quadratic equation: 𝐴𝑥2 + 𝐵𝑥 + 𝐶 = 0
2) solving for the discriminant of a quadratic equation: B2 − 4AC

We know that when the discriminant is positive, there are 2 real roots, when discriminant = 0, there is 1
root. For now, let us ignore the case of a negative discriminant.

However, this is a trick question because of discriminants which could be zero.


Recall in our previous tutorial when we discussed that there are may be tiny inaccuracies in our floating-
point number when doing arithmetic with binary numbers. Therefore, our computed B2 − 4AC may not
return a true zero because of those inaccuracies.

The trick is to use a very small number that is close to zero, that ‘catches’ all these small inaccuracies so that
very small values of the discriminant are essentially regarded as zero.

This question also exposes us to the use of importing the ‘math’ library for square roots.
Week 4_Hands-On_Question 6
Write a program that reads in the coefficients of a quadratic equation and prints the roots
when real roots exist and the message “No real roots” otherwise.
import math

# Get the coefficients A, B and C for Ax^2 + Bx + C = 0


A = float(input("Enter coefficient A: "))
B = float(input("Enter coefficient B: "))
C = float(input("Enter coefficient C: "))

# define a very small positive number below which


# a value is considered zero # check for roots
eps = 0.0000001 if disc > eps:
# two real roots
# calculate the discriminant x1 = (-B + math.sqrt(disc))/(2*A)
disc = B*B - 4*A*C x2 = (-B - math.sqrt(disc))/(2*A)
print("Two real roots:", x1, "and", x2)
elif disc > -eps:
# discriminant is zero or very nearly zero
x1 = -B/(2*A)
print("One repeated root:", x1)
else:
print("No real root.")
Week 4_Hands-On_Question 7
Write a program that asks the user to input the (x,y) coordinate of a point on a 2D plane and
then to compute and report which quadrant it is in.
Recall that points in quadrant 1 have positive x and y, points in quadrant 2 have negative x and
positive y, points in quadrant 3 have negative x and y, whereas points in quadrant 4 have
positive x and negative y.
Note also that you have to check if the given point lies on the x-axis, y-axis, or at the origin.
Hint: define a small epsilon, say epsilon = 1e-7, to differentiate this; beware of computing
equality for floating point numbers.

Hints
Again like Question 6, this question deals with the use of epsilon (eps) as a very tiny number to
represent zero when comparing floating-point numbers when programming.
See the following page for a graphical representation of what Question 7 describes.
Week 4_Hands-On_Question 7
𝑦

Quadrant 2 Quadrant 1
Dotted line
Dotted line
with a value of Dotted line
with a value of
-eps on 𝑥 axis with a value of
+eps on 𝑥 axis
+eps on 𝑦 axis

Dotted line 𝑥
with a value of
-eps on 𝑦 axis

Quadrant 3 Quadrant 4
Week 4_Hands-On_Question 7
# Get inputs # which quadrant?
x = float( input( "input x: " ) ) else:
y = float( input( "input y: " ) ) if x > 0:
if y > 0:
#define the value of eps as 1x10-7 print( "in quadrant 1" )
eps = 1e-7 else:
print( "in quadrant 4" )
# On axis or origin? else:
if abs( x ) < eps: if y > 0:
if abs( y ) < eps: print( "in quadrant 2" )
print( "at origin" ) else:
else: print( "in quadrant 3" )
print( "on y-axis" )
elif abs( y ) < eps:
print( "on x-axis" )

You might also like