Introduction to Software Development - Desklib

Verified

Added on  2023/06/15

|41
|6553
|184
AI Summary
This article covers the basics of software development, including code repositories, software layers, algorithms, and Python programming. It also includes practical sessions with tasks and solutions. Module code: CP30681E
tabler-icon-diamond-filled.svg

Contribute Materials

Your contribution can guide someone’s learning journey. Share your documents today.
Document Page
INTRODUCTION TO SOFTWARE DEVELOPMENT
MODULE CODE: CP30681E
LOG BOOK
STUDENT ID: XXXXXXXXXXX
SCHOOL OF COMPUTING AND ENGINEERING
UNIVERSITY OF WEST LONDON
tabler-icon-diamond-filled.svg

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
ISD lab sheet week 1
In the first week, we learnt about the various uses of a code repository and other
programming tools. We were also introduced to various software and hardware modules, different
application layers and some crucial programming languages.
Questions:
1. What is a code repository (often also called version control system) used for?
Ans. A code repository is a virtual location where one can store his or her codes and
documentations for various programs or applications. A general repository tool or software
provides the techniques to add and maintain several versions of a program, while it still is in its
development stage. One can easily keep track of the changes that have been made over time.
Here, the online code-repository Github has been used to manage the coding tasks for the
assignment and learn a handful from them.
2. Why is it advantageous to use a code repository?
Ans. The advantages of using code repositories are:
i) It enables the collaboration of various team members to work together in a
project, by communicating easily. This allows the different members to download
the modifications or advancements made to the codes and proceed accordingly.
ii) It helps to backup and restore projects.
iii) As it helps to keep track of all the versions of a project throughout its
development phase, one can easily get back codes from the past and use
accordingly.
iv) The documentation feature helps a lot in the understanding of the projects that
are stored there.
3. Describe the different “layers” of Software that exist on a typical computer and explain why
there are different layers of software.
Ans. The different layers of software, which exist in a typical computer, are System Software
and Application software. The application software level helps the program or software to
interact with the user. The user can put in inputs, view instructions and get output on the
application layer of a software. Whereas, the system layer helps the application layer to
Document Page
communicate with the hardware. It converts the user’s inputs in the application layer into
machine language and helps the hardware components to compute them. Further, after
computation this data is changed to user readable language and is communicated back to the
application layer as output.
4. Describe what an algorithm is and explain why it is a useful “tool” to translate from a
human level problem (we can think of) to a computer program.
Ans. Algorithm can be defined as a useful technique that can be used to write down the logic
behind the programs in the write order. It lists the correct order of the instructions or steps
that are to be followed by any program in order to produce the desired output. These are
generally written in plain English language or pseudo codes or via flow-chart diagrams.
It is easier to understand. Novice programmers or people who have no knowledge of
programming can easily understand the logics and instructions behind the execution of the
programs.
Document Page
WEEK 2 - PRACTICAL SESSION 2
In week-2, we were taught about the details of computer programming. We came to know
about the keywords, identifiers, variables, operators and syntaxes that enrich any programming
language and helps in performing the desired operations. We were also taught about high-level
programming languages are converted into machine codes for the computer to understand. Then
we learnt about algorithms, their uses and importance in the field of software development.
Compilers and interpreters were among the other new topics that were taught to us. Then we were
introduced to the basics of the PYTHON language, its history, and language shell that is called as
IDLE.
Finally, we were taught about the various PYTHON keywords the correct ways to implement
each in order to solve regular coding problems.
TASKS:
1) Write an algorithm that describes how to make scrambled eggs, try to use control
words, like IF, WHEN, UNTIL, WHILE, WAIT, AND, OR.
Ans. :
1. Take a few number of eggs.
2. Break them and then pour them in a bowl.
3. Put in some black pepper and salt.
4. Batter the egg yolk for a minute inside the bowl until it becomes fluffy.
5. Now, take a clean frying pan.
6. Put oil in it.
7. Heat the pan.
8. Wait for the oil to get heated up.
9. Put the battered egg into the pan
10.While egg is not cooked,
a. stir the eggs slowly in the frying pan
b. End while
11.If any other ingredients are needed
a. Add other ingredients like red chillies, cheese etc.
12.End if
13. Put the scrambled egg in a plate and serve.
2) Is Idle (the Python language shell) an Interpreter or an Compiler or both? Explain
your answer.
Ans. Python’s language shell – IDLE is an interpreter. It takes one command or
instruction at a time, execute it, and retreats to the Development Environment in
tabler-icon-diamond-filled.svg

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
case any error is come across in any of the line. It waits to produce further
compilation report till the earlier error is solved.
3) Write a command in the Idle shell that says “Hello world”
4) Write a program that produces the following output:
Hello World
I am in my ISD class right now
Ans.
Program :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
print("Hello World") # print command display output on screen
print("I am in my ISD class right now")
Document Page
5) Write a program that asks the user for his/her name and produces an output
like:
Hi there, what is your name?
>User input to be read<
Hello
“User name”
How are you?
Ans. :
PROGRAM :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
name = input("Hi there, what is your name? ") #input takes input from the keyboard
print("Hello")
print(name)
print("How are you?")
Document Page
WEEK 3 – PRACTICAL SESSION 3
This week we learnt about the basics of the Python language. We learnt how to use # or hash to
write a single line comment. Then, we were taught to write programs, save them, compile them,
debug the errors and finally execute the programs.
Next we learnt about variable, data types of variable in python and how to convert values to
different data types using type casting commands like int(), float(), str().
Finally we learnt to create account the github.com website and upload programs in it.
TASKS:
1) Write a program that asks for two numbers (Python has all the basic
mathematical functions in place, like +,- etc.), adds them up and displays the
result.
Ans.:
PROGRAM:
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
number1 = int(input("Enter First number: "))
number2 = int(input("Enter Second number: "))
sum = number1 + number2
print("The sum = ", sum)
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
2) Answer the questions by implementing the code and run it.
a) What will the output be from the following code?
num = 4
num*=2
num1=num+2
num1+=3
print(num1)
Ans. Output: 13
b) What do the following lines of code output? Why do they give a different
answer?
print(2 / 3)
print(2 // 3)
Ans.:
0.6666666666666666
0
‘/’ does normal division by producing results in decimal values.
‘//’ does integer division only and therefore returns the floor value of the divided result.
3) All of the variable names below can be used. But which of these is the better
variable name to use?
A a Area AREA area areaOfRectangle AreaOfRectangle
Ans. areaOfRectangle is the best option to use as it uses the valid camel case variable
naming notation. Further, it conveyes the entire task that the variable is ought to
perform.
4) Which of these variables names are not allowed in Python? (More than one might
be wrong.)
apple APPLE Apple2 1Apple account number account_number
account.number accountNumber fred Fred return return_value
5Return GreatBigVariable greatBigVariable great_big_variable
great.big.variable
Document Page
Ans. 1Apple, account number, account.number, return, 5Return and great.big.variable are the
names that are not allowed to be used as variable names in Python.
WEEK 4 – PRACTICAL SESSION 4
In the 4th week, we were taught about the use of python’s various keywords, variable
declarations, data types and type casting methods or conventions. We also learnt about the
operator precision through the use of logical, mathematical and bit-wise operators. ). Further, we
also learnt the use of escape sequence characters to get formatted output. String concatenation
and repeating characters were also introduced. Finally, we learnt in details the various types of
errors that exist in python programming, such as syntax errors, runtime errors and logical errors.
TASK:
1. Explain the mistake in the following code:
radius = input("Radius:")
x = 3.14
pi = x
area = pi * radius ** 2
Ans. : The input command returns a string version of the user’s input. Therefore, when
trying to perform the multiplication with a float value in area = pi * radius ** 2 there will be
a mismatch of datatypes and the operations will not take place, instead an error will be
posted.
2. Explain the mistake in the following code:
x = 4
y = 5
a = 3(x + y)
Ans.: a = 3(x + y) will produce an error. This might be a correct mathematical operation but in case
of Python programming, the ‘*’ operator must be used to instruct the multiplication operation.
There it must be: 3*(x+y)
3. Explain the mistake in the following code:
radius = input(float("Enter the radius:"))
Ans. Here the position of input and float is a mistake. Float cannot be used to typecast direct string
messages. It should be: radius = float(input(“Enter the radius : “))
Document Page
4. Why does this code not calculate the average?
print(3 + 4 + 5 / 3)
Ans. The above code defies the proper use of operator precedence. The code will divide 5 by 3 and
add 3 and 4 to its result. There must be brackets to couple the addition part to be divided solely by
3, i.e., (3 + 4 + 5 )/ 3.
5. Consider the following code:
x = 19.93
y = 20.00
z = y – x
print(z)
The output is 0.0700000000028 Why is that so?
Improve the code so that the output is to two decimal places.
Ans. : Both x and y are float datatype variables. Thus, the output is a float type value with
complete precision of 13 digits.
To have the output in two decimal places : print (“%.2f”, %z)
6. Find at least three compile-time errors:
int x = 2
Print (x, squared is, x * x)
xcubed = x *** 3
Ans.:
1. int cannot be written to declare a variable. This would return an Invalid Syntax error.
2. Print must not be in caps. It should be print()
3. Inside the print statement, the message ‘squared is’ is kept in the open. The program
will not recognize it as a variable. It should be put in “ “.
4. *** is an invalid use of operators.
7. Find two run-time errors:
from math import sqrt
X = 2
Y = 4
print(“The product of “, x, “and”, y, “is”, x + y)
print(“The root of their difference is “, sqrt(x – y))
tabler-icon-diamond-filled.svg

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Ans.:
1. In the first print statement promises to print the same of x and y, instead prints the
product.
2. The second print statement tries to find the square root of a negative number, as x<y.
8. Write statements to prompt user for their name and age
Write a print statement to output:
Hello ____, next year you will be ____ years old!
Ans. :
Program :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print("Hello ", name, ", next year you will be ", age+1, " years old!")
Document Page
9. Given that radius is 2 and area is calculated as 12.5678, use string format operators to print
the values of the variables radius and area so that the output looks like this:
Radius is: 2
Area is: 12.57
Ans.:
print(“Radius is: \t %d”, 2)
print(“ Area is: \t %.2f”, 12.5678)
10. What are the values of the following expressions, assuming that p is 17 and q is 18?
i. p // 10 + p % 10
Ans. 17 // 10 + 17 % 10 = 8
ii. p % 2 + q % 2
Ans. 17 % 2 + 18 % 2 = 1
iii. (p + q) // 2
Ans. (17 + 18) // 2 = 17
iv. (p + q) / 2.0
Ans. (17 + 18) / 2.0 = 17.5
Document Page
WEEK 5 – PRACTICAL SESSION 5
TASK:
1. Which of the following conditions are true, if a = 13 and b = 14 ?
a) a + 1 <= b :True
b) a + 1 >= b :True
c) a + 1 != b : False
2. Explain the mistake(s) in the following code:
myage = input(How old are you)
Print(Hi there, you are +myage +old)
Ans. :
1. In the input command, the string message ‘How old are you’ should be enclosed in-
between “ ”
2. In the print statement, the string message Hi there, you are old should be in “ “. Also,
the ‘print’ command must begin with a lowercase ‘p’.
3. The myage variable is needed to accept an integer value. Therefore, it is necessary to
type caste the input statement into int
4. While concatenating the myage value to the messages it is either preferable to convert
it to string using str() or use ‘,’ commas.
3. Explain why the following code won’t really add the two “numbers”:
number1 = input("Enter first number")
number2 = input("Enter second number")
result = number1 + number2
print(“The result is ”+result)
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
Ans.: This code will concatenate the user’s inputs. The absence of the type casting command, the
program reads inputs as strings and perform the addition function like concatenation.
4. Write code to calculate the average of: {3, 11, 78, 112, 4, 18} in one
single line of code.
Ans. :
# -*- coding: utf-8 -*-
"""
Created on
@author: duggal
"""
print(sum({3,11,78,112,4,18})/6)
5. Write a program that asks the user for an integer number and then prints out the
remainder after the number is divided by 7.
Ans. :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
num = int(input("Enter an integer number: "))
Document Page
rem = num % 7
fits = num // 7
print("Remainder after dividing by 7 = ", rem)
6. Expand the above program (5.) by also printing out how often the number 7 “fits”
into the number the user entered.
Ans. :
Program :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
num = int(input("Enter a integer number : "))
rem = num % 7
fits = num // 7
print("Remainder after dividing by 7 is :", rem)
print("number 7 fits is : ", fits, " times")
Document Page
tabler-icon-diamond-filled.svg

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
WEEK 6 – PRACTICAL SESSION 6
We learnt the use of flow control structures, repetitive structures and selection structures
were introduced. We also covered the conditional if-elif-else commands alongside the use of
iterative statements like while and for loop.
TASK:
1. What is the error in this statement?
if scoreA = scoreB :
print("Tie")
Ans. : The error is in using assignment operator = in place of the check equality operator ==.
The correct command would be:
If scoreA == scoreB :
print(“Tie”)
2. Supply a condition in this if statement to test if the user entered a “Y”:
userInput = input("Enter Y to quit.")
if . . . // supply statement
print("Goodbye") // if the user entered “Y”
Ans. :
If userInput == “Y”:
print(“Goodbye”)
3. Find the errors in the following if statements, correct where necessary.
a) if x > 0 then :
print(x)
Ans. ‘then’ is not used in if statements. It should be:
if x > 0:
Document Page
print(x)
b) if 1 + x > x ** sqrt(2) :
y = y + x
Ans. :
If (1+x) > x * sqrt(2) :
y = y + x
c) if x = 1 :
y += 1
Ans.:
if x == 1 :
y += 1
d) letterGrade = "F"
if grade >= 90 :
letterGrade = "A"
if grade >= 80 :
letterGrade = "B"
if grade >= 70 :
letterGrade = "C"
if grade >= 60 :
letterGrade = "D"
Ans. :
letterGrade = “F”
if grade >= 90 :
letterGrade = “A”
elif grade >= 80 :
letterGrade = “B”
elif grade >=70 :
letterGrade = “C”
elif grade >= 60 :
Document Page
letterGrade = “D”
4. Using the flow chart below, construct the if, elif, else control structure necessary
to implement the flow chart.
Complete your program to describe the earthquake by asking the user to enter a
magnitude on the Richter scale and print out the effect that magnitude would have
had (e.g. “Many buildings destroyed”).
Ans. :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
richter = float(input("Enter the magnitude on richter scale : "))
if richter >= 8.0 :
print("Most structure fall")
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
elif richter >= 7.0:
print("Many building destroyed")
elif richter >= 6.0:
print("Many building considerably damaged, some collapse")
elif richter >= 4.5:
print("Damage to poorly constructed buildings")
else:
print("No destruction of buildings")
5. Write a program that sets a password as “changeme” and asks the user to enter
the password and keeps asking until the correct password is entered and then says
“Accepted”.
The program should count how many attempts the user has taken and tell them after
they have been accepted.
Extra Challenge:
If the user takes more than 5 attempts the program should say, “Access denied,
please press enter to exit and contact security to reset your password”
Ans. :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
Document Page
password = "changeme"
passw = ""
count = 0
while(password != passw):
passw = input("Enter the password : ")
count += 1
if password == passw:
print("Accepted")
break;
if count == 5:
print("Access denied, please press enter to exit and contact security to reset your password")
break;
print("Number of attempts: ", count)
7. What do the following nested loops display? Hand trace.
for i in range(3) :
for j in range(1, 4) :
print(i + j, end="")
print()
Ans. :
i j print
0 1 1
Document Page
2 2
3 3
1 1 2
2 3
3 4
2 1 3
2 4
3 5
8. Write a program that will generate a table to print powers of the first 5 numbers.
Your output should be similar to the sample given below.
Ans. :
Program :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
for x in range(1, 6):
sqr = x * x
cube = x * x * x
print(x, "\t", sqr, "\t", cube)
tabler-icon-diamond-filled.svg

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Document Page
WEEK 7 – PRACTICAL SESSION 7
Here we learnt about the various data structures used in Python. These includes lists,
tuples, arrays, strings, dictionaries and so on. We also practiced the various functions that can be
used to with these structures.
TASK:
1. Assume the following list: a = [ 66.25, 333, 333, 1, 1234.5 ]
If you perform the following operations on the list:
a.insert(2, -1)
a.append(333)
What will the list look like?
Ans. [66.25, 333, -1, 333, 1, 1234.5, 333]
Now you perform:
a.index(333)
What will the output of this operation be?
Ans. 1
Now you perform:
a.remove(333)
What will the list look like?
Ans. [ 66.25, -1, 1, 1234.5]
Now you perform:
a.reverse()
What will the list look like?
Ans. [1234.5, 1, -1, 66.25]
Now you perform:
a.sort()
What will the list look like?
Document Page
Ans. [-1, 1, 66.25, 1234.5]
2. Write a short program to create a list of squares for numbers up to 10. Start with an empty
list called squares and append squares of numbers from 0 up to 10. Print the contents of
your list.
Ans.:
Program
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
num = []
for x in range(11):
sq = x * x
num.append(sq)
print(num)
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
3. nums = []
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
nums.append((x, y))
print(nums)
What is the output from above?
Ans. :
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
4. Create a program that will keep track of items for a shopping list. The program
should start with an empty list and keep asking for new items until nothing is
entered (no input followed by enter/return key). The program should then
display the full shopping list.
Ans.:
Program :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
shoppinglist = []
setFlag = 1
item = ""
while(setFlag != 0):
item = input("Enter the item in shopping list : ")
if item == "":
setFlag = 0
Document Page
break;
else:
shoppinglist.append(item)
print(shoppinglist)
5. Write a program that will ask the user to enter two short sentences and then:
- Concatenate the two sentences into one long sentence
- Split the sentence into a list of words
- Sort the words in alphabetical order and print them out
- Print the total number of words contained in your list
- Create a dictionary that will store each word together with the count of the
occurrence of each word in your sentence.
Print each item from the dictionary
Ans. :
Program :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
sentence1 = input("Enter first sentence: ")
sentence2 = input("Enter second sentence: ")
Document Page
newSentence = sentence1 + sentence2
print("New sentence: ", newSentence)
words = newSentence.split(" ")
print("The words here are: ",words)
words.sort()
print("The sorted words are: ",words)
print("Number of words in ",newSentence,": ", len(words))
tpl = tuple(words)
dict = {}
for eachWord in tpl:
dic = dict.fromkeys(tpl,tpl.count(eachWord)) #to count the occurance of each word
print(str(dict))
tabler-icon-diamond-filled.svg

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
WEEK 8 AND 9 – PRACTICAL SESSION 8
Here, we learnt about creating and calling functions to get various operations done, neatly.
We also learnt the use of return statements and parameters to pass values between different
functions. The use of global variables also helped to initialize and use variables in the global
context.
TASK :
Consider this function:
def mystery(x, y) :
result = (x + y) / (y - x)
return result
What is the result of the call mystery(2, 3)?
Ans. : 5
What does this program print?
def main() :
a = 5
b = 7
print(mystery(a, b))
def mystery(x, y) :
z = x + y
z = z / 2.0
return z
main()
Ans. : 6
Document Page
What does this program print?
def main() :
a = 4
print(mystery(a + 1))
def mystery(x) :
y = x * x
return y
main()
Ans. : 25
Consider this function that prints a page number on the left or right side of
a page:
if page % 2 == 0:
print(page)
else :
print("%60s%d" % (" ", page))
Introduce a function that returns a Boolean to make the condition in the if
statement easier to understand.
Ans. :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
def prnpage(page):
if page % 2 == 0:
return True
Document Page
else:
return False
def main():
page = int(input("Enter the page num: "))
result = prnpage(page)
if result == True:
print(page)
else:
print("%60s%d" % (" ", page))
main()
Transform the following instructions into a function called count_spaces.
Define a main function that will ask the user to enter some input and call
the count_spaces function to return the number of spaces.
# Counts the number of spaces
spaces = 0
for char in userInput :
if char == " " :
spaces = spaces + 1
Ans. :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
def countSpace(sentence):
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
spaceCount = 0
for character in sentence :
if character == " ":
spaceCount += 1
return spaceCount
def main():
sentence = input("Enter sentence:")
spaceCount = countSpace(sentence)
print("There are ", spaceCount," spaces.")
main()
Consider this recursive function:
def mystery(n) :
if n <= 0 :
return 0
else:
return n + mystery(n - 1)
What is mystery(4)?
Document Page
Ans. : The function will return 24 and the factorial of 4 is also 24
def mystery(n) :
if n <= 0 :
return 0
else:
return mystery(n // 2) + 1
What is mystery(20)?
Ans. 5
Program :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
def mystery(number) :
if number <= 0 :
return 0
else:
return (mystery(number // 2) + 1)
def main():
number = mystery(25)
print(number)
main()
Document Page
Consider these functions:
def f(x) :
return g(x) + math.sqrt(h(x))
def g(x) :
return 4 * h(x)
def h(x) :
return x * x + k(x) - 1
def k(x) :
return 2 * (x + 1)
Without actually compiling and running a program, determine the results
of the following function calls:
a. x1 = f(2) …Output : 39
b. x2 = g(h(2)) …Output: 100
c. x3 = k(g(2) + h(2)) …Output: 36
d. x4 = f(0) + f(1) + f(2) …Output: 5
e. x5 = f(-1) + g(-1) + h(-1) + k(-1) …Output: 0
Consider the following function:
def f(a) :
if a < 0 :
return -1
n = a
while n > 0 :
if n % 2 == 0 : # n is even
n = n // 2
elif n == 1 :
return 1
tabler-icon-diamond-filled.svg

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
else :
n = 3 * n + 1
return 0
Perform traces of the computations f(-1), f(0), f(1), f(2), f(10), and f(100).
Ans.
f(-1) Output: -1
f(0) Output: 0
f(1) Output: 1
f(2) Output: 1
f(10) Output: infinite loop
f(100) Output: infinite loop
Document Page
WEEK 10 – ISD LAB SHEET SESSION 10
In week 10, we learnt to create classes and objects and use them to build larger programs.
TASK :
1 a) Write a class “Student” with a state that stores information about the students surname, last
name, student number and course. The behaviour of the “Student” class should enable a student
object to get and set each of the Student class variables and to print out all of the Student’s
information.
Ans. :
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
class student:
def __init__(stu, surname, firstname, stunum, course):
stu.surname = surname
stu.firstname = firstname
stu.stunum = stunum
stu.course = course
def get_Surname(stu):
return stu.surname
def set_Surname(stu,surname):
stu.surname = surname
Document Page
def get_Firstname(stu):
return stu.firstname
def set_Firstname(stu,firstname):
stu.firstname = firstname
def get_Studentnumber(stu):
return stu.stunum
def set_Studentnumber(stu, stunum):
stu.stunum = stunum
def get_Course(stu):
return stu.course
def set_Course(stu,course):
stu.course = course
def __str__(stu):
return "Surname: %s \t FirstName: %s \t Student number: %s \t Course taken: %s " %
(stu.surname, stu.firstname, stu.stunum, stu.course)
1 b) Write a program with a main function that imports the Student class, creates a student objects
and prints and changes some of the information (like surname, last name) of the student object.
Ans:
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
from student import student
def main():
Surname = input("Enter student's surname: ")
Firstname = input("Enter student's first name: ")
StuNo = input("Enter student number: ")
Course = input("Enter student's course: ")
stuObj = student(Surname,Firstname,StuNo, Course)
print("Initial details...",stuObj)
print("Change Surname...")
Surname = input("Enter new surname: ")
stuObj.set_Surname(Surname)
print("Change course...")
Course = input("Enter the name for new course: ")
stuObj.set_Course(Course)
print("Updated student details...",stuObj)
main()
Document Page
2 a) A simulated cash register that tracks the item count and the total amount looks like this: due
class CashRegister :
def __init__(self) :
self._itemCount = 0
self._totalPrice = 0.0
def addItem(self, price) :
self._itemCount = self._itemCount + 1
self._totalPrice = self._totalPrice + price
def getTotal(self) :
return self._totalPrice
def getCount(self) :
return self._itemCount
def clear(self) :
self._itemCount = 0
self._totalPrice = 0.0
2 b) Write a TestRegister class to test the addItem, getTotal, getCount and giveChange methods of the
CashRegister class
# -*- coding: utf-8 -*-
"""
Created on
@author:
"""
from cashregister import cashRegister
def main():
cashReg = cashRegister()
price=1
print("Enter 0 to stop adding items...")
Document Page
while price!= 0:
price = float(input("Enter price of the new item to be added: "))
if price != 0:
cashReg.addItem(price)
totalPrice = cashReg.getTotal()
itemCount = cashReg.getCount()
print("Total price: ", totalPrice)
print("Item count: ", itemCount)
main()
NOTE :
TO ACCESS THE GITHUB REPOSITORY OF THE CODE :
PLEASE GO TO THE FOLLOWING LINK
tabler-icon-diamond-filled.svg

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
https://github.com/UserPython123/python
chevron_up_icon
1 out of 41
circle_padding
hide_on_mobile
zoom_out_icon
[object Object]

Your All-in-One AI-Powered Toolkit for Academic Success.

Available 24*7 on WhatsApp / Email

[object Object]