Vous êtes sur la page 1sur 10

Question 1 [30 marks] But only 10 questions are shown in this sample

This question consists of 30 multiple choice questions. Answer all the questions on the
multiple-choice answer sheet given. There is only one correct answer per question. Choose
your answer and shade the corresponding letter in the answer sheet.
1. What will be printed by the following Python script:
def main():
v = '123'
print('Value is', v*3)
main()

a. The script caused a syntax error as the string '123' cannot be multiplied by an
integer
b. This script executes and produces the following output:
Value is 123123123

c. The output is:


Value is 1233

d. The output is:


Value is 369

2.

Which of the following expression will results in True?


a. 'a' in "ABC"
b. 'a' not in "ABa"
c. 'a' == 'A'
d. None of the above

3.

The docstring in Python starts and ends with


a. """
b. ###
c. "'"
d. ///

4.

The expression (3 // 4) * 4.0 evaluates to


a.
0
b.
3
c.
0.0
d.
3.0

5.

Given that x is 1, and y is 4, what value is assigned by the statement:


w = x * x * x / y * y * y

a.
b.
c.
d.

2.5
0
4.0
4

6.

What is display when the following command is entered interactive in Python shell
>>> type(10.0)

a.
b.
c.
d.
7.

<class 'str'>
<class 'float'>
<class 'int'>
<class 'bool'>

What is printed on screen for the following Python fragment?


print('3' > 5)
a.
b.
c.
d.

3>5
False
bool
Nothing is printed as the statement will cause a type error

8. Value that a user must supply to stop a loop is called a(n) ________ value.
a. ending
b. sentinel
c. terminal
d. stopper
9.

Which of the following statements about function definition in Python is correct?


a. A function must be declared with at least one parameter
b. You can only define function that returns one value
c. There must be at least one return statement when defining a function
d. We can define a function that return value of any type, including user-defined
data type

Question 10 will be based on the following fragment code:


numList = []
for value in range(50):
numList.append(random.randrange(1,100)- 20)
count = 0:

10. What does the value of the variable count represent in the following fragment?
for value in numList:
if value % 2 != 1:
count += value

a.
b.
c.
d.

Sum of all even integers in the array


Number of odd integers in the array. If value%2!=0count+=1
Number of even integers in the array. Count+=1
Number of positive integer in the array. Value>0count+=1

def main():
#variable declarations
totalSales=0.0
totalTshirtSold=0
Question 2 [15 marks]#promt user for data(priming read)
Size=input(Enter T-shirt size(S,M,L) or Q to quit:)
For the question presented#test
below,for
yousentinel
are required to solve it by providing a Python program.
While <not sentinel>:
Whilein size.upper()
!=Q:
The Apollo Shop specialised
selling only Polo
T-shirts in Kuta Street. The Polo T-shirts
While size.lower() !=q:
sold are in three different While
sizes not(size
Small, Medium,
and
Large. The price for each type of shirts
in [Q,q]):
is as followed: Small $30.00,
Medium - and
$45.00,
and Large - $60.00. To encourage more
While size!=Q
size!=q:
data
tourists to buy in bulk, the shop #read
owner more
decides
to give a 10% discount if 5 or more T-shirts
Qty=int(input(Enter quantity:)
are bought for any type of size in #use
a single
receipt. to
selection
compute summary data
ifwrite
sizea in[S,s]:
You are employed by the owner to
Python program that will compute the total T-shirts
thisSales=30*qty
sales for the day.
elif size in [M,m]:
thisSales=60*qty
else:
The program must allow the user to enter the size of T-shirts follows by the quantity, it then
thisSales=90*qty
calculates and displays the total cost
for the
if qty
>=5:T-shirts sold in each sales. Only one type of size
thisSales=thisSales+thisSales*0.1
is to be considered in each sale. At the end of the day, the total amount collected and the total
OR
T-shirts sold will be displayed.
thisSales=thisSales*(1-0.1)
OR
You may assume that the user will alwaysthisSales=0.9*thisSales
enter valid character, and thus you dont have to do
any validation for this program. totalSales+=thisSales
totalTshirtSold+=qty

The following shows a sample run


of a correctly
implemented
program:
#display
summary
data
Print(for,qty,T-shirt of size +size+\
,the
$+str(thisSales))
Enter T-shirt size (S, M, or
L), cost
Q to is
quit:
S
#promt user for data(follow-up data)
Enter quantity? 3
Size=input(Enter T-shirt size(S,M,L) or Q to quit:)

For 3 T-shirts of size 'S', the cost is $90.0

#use selection to display final result


Qsales=,totalSales)
to quit: s
T-Shirt sold=,totalTshirtSold)

Enter ticket type (S,Print(Total


M, or L),
Enter quantity? 5
Print(Total
For 5 T-shirts of size 's', the

cost is $135.0

Enter ticket type (S, M, or L), Q to quit: M


Enter quantity? 2
For 2 T-shirts of size 'M', the cost is $90.0
Enter ticket type (S, M, or L), Q to quit: L
Enter quantity? 6
For 6 T-shirts of size 'L', the cost is $324.0
Enter ticket type (S, M, or L), Q to quit: q
Total sales = $639.0
Total T-shirts sold = 16

When the user enters Q (or q) for the T-shirt size the program should take this to mean that no
more data need to be processed and terminate after showing the final report as shown above.

Question 3 [15 marks]

Each of the following parts is to be answered by writing a complete definition of one Python
function. You do not have to create a complete class nor a complete program. Credit will be
based on the correct use of arguments, and meaningful method names, as well as correct
Python syntax and logic. Unless specifically stated, the methods should not interact directly
with standard input or output streams, nor should they interact directly with any GUI
components.
def frequency(alist,ch):
count=0
for I in range(len(alist)):
if alist[i]==ch:
count+=1
return count
OR
def frequency(alist,ch):
count=0
for ele in alist:
if ele==ch:
count+=1
return count

(a) Write a function called frequency that accepts two parameters the first is a list of
characters and the second is a character. The function should return how many times the
character parameter appears in the list. NOTE: You are not allowed to use the count
method of List.
def frequency(alist,ch):
count=0
for I in range(len(alist)):
if alist[i]==ch:
count+=1
return count
OR
def frequency(alist,ch):
count=0
for ele in alist:
if ele==ch:
count+=1
return count

(b) Table 1 below shows the new rate for fixed-line telephone call charges for whole
Malaysia. The charge for each call depends on the zone as well as for how long the call is
made.
Write a Python function named callCharges that accepts TWO parameters both are of
integer type. The first represents the call zone while the second represent the duration of
the call, in minutes. This function should calculate and return the call charges based on
the table given.
Zone
1
2

Charge per minute (in RM)


0.15
0.35

Table 1

3
4

0.75
1.00

def callCharges(zone,duration):
if zone ==1:
charge= 0.15*duration
elif zone ==2:
charge= 0.35*duration
elif zone== 3:
charge= 0.75*duration
else:
charge = 1.00*duration
return charge
OR
def callCharges(zone,duration):
if zone==1:
rate=0.15
elif zone==2:
rate== 0.35
elif zone==3:
rate == 0.75
else:
rate==1.00
return rate*duration

(c) A function that will calculate and return the charges for Internet surfing given the duration
of surfing, in minutes (an integer). Access fee is 1.5 cent per minute.
def charges(duration):
return duration*1.5

(d) The cost of printing a photograph is based on picture size, and whether it is colour or
black and white, as shown in the table below:
Size

3R

5R

Colour

10.00

18.00

Black and White

6.00

11.00

Mode

Write a function that accepts two parameters one for size and one for mode, both are of
type string, and the function should return the cost of printing a photograph.
def cost(size,mode):
if size==3Rand mode==colour:
return 10.00
elif size==3R and mode==Black and White:
return 6.00
elif size==5R and mode==colour:
return 18.00
else:
return 11.00
OR
def cost(size,mode):
if size ==3R:

if mode==Colour:
return 10.00
else:
return 6.00
else:
if mode==colour
return 18.00
else:
return 11.00

Question 4 [15 marks]

Show the output that would be generated by each of the following program fragments.
NOTE: Use for space, i.e. for a space in your output, you write .
a) for i in range(5):0,1,2,3,4
print(i)

b) for i in range(5): i=

0 i= 1 i= 2 i= 3 i= 4

print('i=',i)

c) for i in range(5): i={}

0 i={} 1 i={} 2 i={} 3 i={} 4

print('i={}',i)

d) for i in range(5):

i= 0 i= 1 i= 2 i= 3 i= 4

print('i={}'.format(i))

e) for i in range(5):
print('i={:}'.format(i))

f) for i in range(5):

print('i={:5}'.format(i))

g) for i in range(5):
print('i={:0}'.format(i))

h) for i in range(5):

print(( 'i={:'+str(i+1)+'}' ))

i) for i in range(5):
print(( 'i={:'+str(i+1)+'}' ).format(i))

j) for i in range(5):

print('i={:5}'.format(float(i)))

k) for i in range(5):
print(('i={:.5f}').format(float(i)))

l) for i in range(5):

print(('i={:.'+str(i)+'f}'))

m) for i in range(5):
print(('i={:.'+str(i)+'f}').format(float(i)))

n) for i in range(5):
print('{0:2d} {1:.2f}'.format(i, float(i)))

o) for i in range(5):

print('{1:.2f} {0:2d}'.format(i, float(i)))

Question 5 [15 marks]


Guidelines for a new user-defined Python class are given below. Use the guidelines to write
the complete source code for the class.
The class Employee holds information about an employee in a company. Information stored
includes the name (of type string), age (of type integer), and salary (of type float).
Your task to write the complete source code for the class Student:
(a) Write the initialise method (__init__) for the class Employee. The method should accept
all three attributes for an employee a name, an age, as well as the salary, and should
initialise its objects attributes with these argument values.
(b) For each attribute (instance variable) we need to write a getter and setter method for it.
Write the getter and setter methods for the each of the attributes name, age and salary.
(c) Write the string method (__str__) that returns the detail of an employee in the format:
<name>, aged <age> earns <salary> per month
Assume that a list of Employee objects called 'company' has already been defined and
contains valid Employee objects in its cells.
Write Python fragments code to complete these tasks:
I.
II.
III.
IV.

Add an Employee object to the list named company above


Increase the first employees age by 1.
Find and display the total salary for all stored Employees.
Find and display the names of all Employees who are less than 40 years old.

Class Employee:
def__init__(self,name,age,salary):
self._name=name
self._age=age
self._salary=salary
def getName(self):
return self._name
def getAge(self):
return self._age
def getSalary(self):
return self._salary
def setName(self,newName):
return self.name=newName
def setAge(self,newAge):
return self.age=newAge
def setSalary(self,newSalary):
return self.salary=newSalary
def __str__(self):
return{},age{},earns{:.2f} per month.format(self._name,\
self._age,self._salary)
I)

company.append(Employee(LauSN,20,1000))

II)

company[0].setAge(company[0].getAge()+1)
totalS=o

III)

for emp in company:


totalS+= emp.getSalary()
print(totalS)
avg=totalS/len(company)
print(avg)

IV)

for emp in company:


if emp.getAge()<40:
print(emp.getName())

Vous aimerez peut-être aussi