INF1511 Tutorial+201
INF1511 Tutorial+201
Visual Programming 1
INF1511
Semester 1
School of Computing
IMPORTANT INFORMATION:
This tutorial letter contains ASSIGNMENT SOLUTIONS for 2018 Semester 1.
All other important information is sent to your myLife account and is available on
the module INF1511 website.
CONTENTS
Page
2
INF1511/201/2/2018
3
7. The function used to receive 1 str()
input from users is … 2 input()
3 print()
4 type()
8. What is the value of num3 after 1 8
executing the following code? 2 12
num1=2 3 10
num2=4
if(num1%num2 != 0): 4 6
num3=2*num1+num2
elif(num2%num1 >0):
num3=num1+num2*2
else:
num3=num1+num2
4
INF1511/201/2/2018
5
17. What is the output of the 1 1 3 5 7 9
following code snippet? 2 4 6 8
2
i=1
3 1 3 5
while i <=8:
if i%2 == 0: 4 1 3 5 7
i=i+1
continue
print(i,end=' ')
i+=1
18. What is the output of the 1 2
following code? 2.5
2
print("10/4")
3 0
4 10/4
19. What is the output of the 1 5 8 11 14
following code? 5 8
2
for i in (5,8,11,14,17):
3 5 8 11
if i==11:
4 None of the above
break
print(i,end=' ')
6
INF1511/201/2/2018
4 Option 2 and 3
5 Option 1 and 3
7
Assignment 02 PDF [15]
1. Create a Python program that accepts two numbers as input from the user. The program
should then add the two numbers and print the output. Save the program as sum.py and
add a comment at the beginning of your program. (5)
Marker: 1 Mark for comment in line 1. ½ a mark is rewarded for line 2 & 3 (each). 1
Mark for line 4. 1 Mark for the file name showing correctly in the screenshot.
ii) A screenshot of the output of the program (1).
2. Write a program that prompts the user to enter four integer numbers and then count the odd
and even numbers in the entries. (5)
A sample run:
Enter an integer number: 2
Enter an integer number: 7
Enter an integer number: 4
Enter an integer number: 6
Number of even numbers entered: 3
Number of odd numbers entered: 1
8
INF1511/201/2/2018
cnt_e = 0
cnt_o = 0
for i in range (4):
num = int(input("Enter an integer number: "))
if(num % 2 == 0):
cnt_e += 1
else:
cnt_o += 1
print()
print("Number of even numbers entered:" , cnt_e)
print("Number of odd numbers entered:" , cnt_o)
3. Write a program that repeatedly asks the user to enter a number, either float or integer until
a value -88 is entered. The program should then output the average of the numbers entered
with two decimal places. Please note that -88 should not be counted as it is the value
entered to terminate the loop. (5)
A sample run:
Enter a number(integer or float):5
Enter a number(integer or float):3.2
Enter a number(integer or float):2.1
Enter a number(integer or float):-88
The average of 5 numbers entered is 3.43
#average of numbers entered until -999 is entered as a sentinel value
count = 0
total = 0
num = 0
while(num != -88):
num = float(input("Enter a number(integer or float):"))
if(num != -88):
total = total + num
count = count + 1
avg = total / count
print("The average of %d numbers entered is %.2f" %(count,avg))
OR
#another solution
count = 0
total = 0
num = 0
while(count <= 100):
num = float(input("Enter a number(integer or float):"))
if(num == -88):
break
total = total + num
count = count + 1
avg = total / count
print("The average of %d numbers entered is %.2f" %(count,avg))
9
Assignment 03 MCQ [20]
Question Option Answer
1. … is an example of a mutable 1 Boolean
sequence in Python 2 String
3 Tuple
4 List
5 None of the above
2. The index value of the last element 1 -1
in a list is … 2 0
3 1
4 12
5 z
3. If num is a list variable with five 1 print(num[len(num) - 1])
elements, which print statement 2 print(num[-1])
will output the last element of the
list? 3 print(num[4])
4 All the above
4. What is the output of the following 1 6
code? 2 3
3 2
print(len([(2,4),(6,8),(10, 4 1
12)]))
5 6
5. What is the output of the following 1 sgnimmargorP
code? 2 g-n-i-m-m-a-r-g-o-r-P
3 gnimmargorP
s = "Programming" 4 Programming
r=reversed(s) None of the above
5
for i in r:
print(i, end='')
6. What is the output of the following 1 False
code? 2 True
takeaways 3 KFC
=["KFC","Romans","McDonalds 4 1
"]
print("K" in takeaways)
7. Which of the following statements 1 a=[2*i for i in range(2,6)]
will create and initialise an array a 2 a=[2*i for i in range(4)]
with values 4, 6, 8, 10 3 a=[2*i for i in range(10)]
4 a=[2*i for i in range(4,10)]
8. What is the output of the following 1 [0, 1, 4, 9, 16]
2 [1, 4, 9, 16, 25, 36]
10
INF1511/201/2/2018
14. Which one of the for loops will print 1 for m in months:
elements of the list print(m)
months=["Jan","Feb","Mar"] 2 for i in range(0,len(months)):
one by one? print(months[i])
3 Options 1 and 2
11
15. Which of the statements will alter 1 days.reverse()
the list 2 days.sort()
3 days.append(['Wed', 'Tue',
days=['Mon', 'Tue', 'Wed']
'Mon'])
to
4 None of the above
days=['Wed', 'Tue', 'Mon']?
4 def
12
INF1511/201/2/2018
# listnumwords.py
words= ['One', 'Two', 'Three', 'Four', 'Five']
n= int(input("Enter a number between 1 and 5: "))
if 1 <= n <= 5:
print ("The word is", words[n-1])
else:
print ("Entry is out of range")
2. Write a program that asks the user to enter a sentence and a specific letter to be replaced
with the the % character. If the letter entered does not appear in the sentence, print an
appropriate message. (6)
Hint:- refer to built-in functions for strings.
Sample runs:
(1)
Enter a sentence: I am glad you could make it!
Enter a letter: a
I %m gl%d you could m%ke it!
(2)
Enter a sentence: How are you?
Enter a letter: b
The character does not occur in the sentence.
#string-replace
count_l = 0;
sen = input("Enter a sentence: ")
let = input("Enter a letter: ")
for letter in sen:
if(letter == let):
count_l += 1
if(count_l == 0):
print("The letter does not occur in the sentence.")
else:
sen1 = sen.replace(let, '%', count_l)
print(sen1)
13
3. Write a program that uses a recursive function named printFactors() to print all the
factors of an integer number received from the main program. (5)
A sample run:
Enter an integer number: 12
The factors of 12 are :
1
2
3
4
6
12
14
INF1511/201/2/2018
15
Question Option Answer
3 Python does not support
polymorphism.
4 None of the above
6. In Python, all classes automatically 1 base
extend the built-in … class, which is the
2 self
most general class possible.
3 object
4 None of the above
7. Which file access mode option allows file 1 r+
reading only?
2 r
3 read+
4 read
8. Assuming that a text file file.txt exists 1 f=open('file.txt', r)
with few lines of text, which of the code line=f.read()
snippets will read the entire file?
2 f=open('file.txt', 'r')
line=f.read(1)
3 f=open('file.txt', 'r')
line=f.read(-1)
4 None of the above
3 finally
4 None of the above
16
INF1511/201/2/2018
3 a+
4 A
17
17. If first.txt exists with few lines of text 1 f=open("first.txt", 'r+')
in it which of the given code snippets will for line in f:
read the file and output the lines of text print(line, end = '')
f.close()
one by one to the console?
2 import sys
f=open("first.txt", 'r+')
for line in f:
sys.stdout.write(line)
f.close()
3 f=open("first.txt", 'w+')
lines=f.readlines()
for i in range(0,
len(lines)):
sys.stdout.write(lines[i])
f.close()
4 Option 1 and 2.
18. … is the process of converting structured 1 Pickling
data in Python to data stream format.
2 Unpickling
3 Deserialization
18
INF1511/201/2/2018
import linecache
line=linecache.getline('classlist.txt', 2)
print ('The content of the third line is:', line)
2. Create a class Publication with public member variables publisher, title and
price with the following specifications: (18)
• Add init() method of the class that initialises string member variables to empty strings
and numeric values to 0.
• Add two more methods to the class: populate() and display().
o The populate() method is used to assign values to the member variables of the
class.
o The display() method is used to display the member variables of the class.
• Derive a class Book from Publication.
o The class Book has two public member variables of its own: ISBN and
authorname.
o Define the init() method for the class Book that initialises string member
variables to empty strings and numeric values to 0, and also override the
populate() and display() methods of the base class.
o Create an instance bookObj of the class Book in a main program.
• The main program should then prompt the user to enter the following values:
Publisher : Romfort
Title : Computing for beginners
Price: 280
ISBN: 123456
Author Name: Jo Mahlangu
• The above attributes should be assigned to the instance bookObj using its
populate() method.
o Then display all these attributes back to the console using the display() method
of the instance bookObj.
A sample run:
Enter publisher name: Romfort
Enter title: Computing for beginners
Enter price: 280
Enter ISBN number: 123456
Enter author name: Jo Mahlangu
19
#single inheritance - class Publication
class Publication(object):
def __init__(self):
self.publisher = ""
self.title = ""
self.price = 0.0
def populate(self, pub,t,pr):
self.publisher = pub
self.title = t
self.price = pr
def display(self):
print("Publisher:", self.publisher)
print("Title:", self.title)
print("Price: R%.2f " %(self.price))
class Book(Publication):
def __init__(self):
Publication.__init__(self)
self.ISBN = 0
self.authorname = ""
def display(self):
Publication.display(self) #self parameter is required
print("ISBN:", self.ISBN)
print("Author Name:", self.authorname)
#main program
bookObj = Book()
pb = input("Enter publisher name: ")
t = input("Enter title: ")
pr = float(input("Enter price: "))
iNo = int(input("Enter ISBN number: "))
a = input("Enter author name: ")
bookObj.populate(pb,t,pr,iNo,a)
print()
print("The details of the book are:")
bookObj.display()
20
INF1511/201/2/2018
21
Assignment Evaluation Rubric
22
INF1511/201/2/2018
Requirement Solution
(must be submitted)
1 Copy & Paste a print
screen of the program
user interface(UI) in
design time.
4 Copy & Paste the See the code for .pyw file below.
complete code of the
source file which
invokes your UI design.
23
Item 4
#callcountchar.pyw
import sys
from countchar import *
class MyForm(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_DlgCountchar()
self.ui.setupUi(self)
#the following line will call occur() when btnCount is clicked
self.ui.btnCount.clicked.connect(self.occur)
def occur(self):
#we should add validation to check if the edit box is empty.otherwise python will throw error
l = len(self.ui.edtString.text())
if l != 0:
if len(self.ui.edtChar.text()) != 0:
line = self.ui.edtString.text()
ch = self.ui.edtChar.text()
numChar = 0
for i in range(0,l):
if(line[i].lower() == ch.lower()): #for case-insensitive count
numChar += 1
self.ui.lblOccur.setText("Number of occurences: " + str(numChar))
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
24
INF1511/201/2/2018
25
Assignment Evaluation Rubric
Requirement Solution
(must be submitted)
1 Copy & Paste a print
screen of the program
user interface(UI) in
design time.
26
INF1511/201/2/2018
# calllist.pyw
import sys
from hospital import *
from PyQt4.QtGui import *
27
class MyForm(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_DlgHospital()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.btnAdd,
QtCore.SIGNAL('clicked()'), self.addlist)
QtCore.QObject.connect(self.ui.btnDelete,
QtCore.SIGNAL('clicked()'), self.delitem)
QtCore.QObject.connect(self.ui.btnDeleteAll,
QtCore.SIGNAL('clicked()'), self.delallitems)
self.ui.lstPatients.takeItem(self.ui.lstPatients.currentRow())
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
© 2018 Unisa
28