TRHHTRH
TRHHTRH
TRHHTRH
Python
Sahana Kumaraswamy /
Author(s)
Roy Antony Arnold G
Authorized by Satheesha B.Nanjappa
Version 1.0
COPYRIGHT NOTICE
© 2017 Infosys Limited, Bangalore, India. All Rights Reserved.
Infosys believes the information in this document is accurate as of its publication date; such
information is subject to change without notice. Infosys acknowledges the proprietary rights of
other companies to the trademarks, product names and such other intellectual property rights
mentioned in this document. Except as expressly permitted, neither this documentation nor any
part of it may be reproduced, stored in a retrieval system, or transmitted in any form or by any
means, electronic, mechanical, printing, photocopying, recording or otherwise, without the prior
permission of Infosys Limited and/ or any named intellectual property rights holders under this
document.
Dr. P. Suresh /
Sahana Kumaraswamy / Kalpana Balaraman
1.0 Dec 2015 Initial Draft
Roy Antony Arnold G /
K.N.Vani
Context
This document contains assignments to be completed as part of the hands on session for
the course – Object Oriented Programming using Python
Guidelines
The assignments guide has been designed to give hands on experience to
map/apply the concepts learnt in the theory session with practical assignments.
The assignments have been categorized into solved assignments to hand hold a
beginner, partially solved assignments to begin trying out on their own and
unsolved assignments to let learners write code completely on their own
These assignments contain coding exercises, debugging exercises, coding
standards exercises assignments
The case study based assignments are threaded, which can be built incrementally.
This will help understanding the concepts and building a complete application
The estimated time would help a learner to solve problems given a deadline
The assignments need to be completed as instructed by the facilitators
Assignments marked as Demo can be used by the faculty during lecture and
students need to compile and execute it using Eclipse
About Eclipse
To start the Eclipse IDE, double click the Eclipse.exe, You may create a shortcut on
your desktop
Once started a prompt will open which will ask you to enter the workspace information as
shown in Fig. 3. A workspace is a folder where all the projects created in Eclipse are
saved. Create a folder in your desired path and give the correct path as shown below.
Once loaded, you will see the Welcome tab as shown in Fig. 4. Close this Welcome tab
to go to the Project Window.
Next go to the Window menu and select the perspective as Python perspective as shown
in Fig. 5.1 and Fig 5.2. (Window Open Perspective PyDev)
Selecting the PyDev perspective will give you the screen as shown in Fig. 6.
In Eclipse a workspace can contain one or more projects and each project usually
contains a Python application. Each application may contain one or more Python files.
To create a new project, go to File New Project as shown in Fig. 7.
Select the option PyDev Project under the PyDev category as shown in Fig. 8.
This will create a project and you can see the same in the package explorer along
with the path of the interpreter configured in the last step as shown in Fig. 10.
To write your first Python program you must first create a PyDev Module. Right click
on the project and go to New PyDev MOdule as shown in Fig. 11.
Enter the Package name and PyDev Module name as shown in Fig. 12 and then
click on finish.
Packages are like directories and PyDev modules are like files. Packages will be
explained later.
This will add a Package and a PyDev module in the package to the project as shown
in Fig. 13.
You can also create new PyDev modules in the package created
The output of the program will be displayed in the Console Tab as shown in Fig.15.
Summary of this assignment: You have now learnt how to create projects, how to
create and execute a simple Python program using Eclipse IDE.
Objective: Given a real world problem, be able to understand the need for programming
fundamentals such as identifiers, variables, data types etc
bill_id: 1001
customer_id: 101
bill_amount: Rs.199.99
Analyze the above problem statement and answer the following questions:
1. What do you think is needed to write a program to implement the solution for the above
problem statement?
Summary of this assignment: In this assignment, you have understood the need of a
high level programming language and programming fundamentals such as identifiers,
variables, data types, operators etc
Problem Description: For the previous assignment, identify the data types that may be
used to represent bill id, customer id and bill amount.
Summary of this assignment: In this assignment, you have learnt to identify the data
type for the variables based on the real world problem
Output:
Summary of this assignment: In this assignment, you have learnt to make use of format
specifiers for different type of data variables based on the real world problem
Problem Description: Write a Pseudocode and Python program to implement the real
world problem discussed in Programming constructs in Python Assignment 2. Compile
and execute the program using Eclipse IDE.
INITIALIZE_VARIABLES_DISPLAY
1. bill_id = 1001
2. customer_id = 101
3. bill_amount = 199.99
4. display "Bill Id:", bill_id
5. display "Customer Id:", customer_id
6. display "Bill Amount:Rs.", bill_amount
bill_id = 1001
customer_id = 101
bill_amount = 199.99
print("Bill Id:%d" %bill_id)
print("Customer Id:%d" %customer_id)
print("Bill Amount:Rs.%f" %bill_amount)
Output:
Monthly Pay = Number of hours worked in a week * Pay rate per hour * No. of weeks in
a month
Note:
The number of hours worked by the employee in a week should be considered as 40,
Pay rate per hour should be considered as Rs.400 and
Number of weeks in a month should be considered as 4
Write Pseudo code and Python program in Eclipse to implement the above real world
problem.
Summary of this assignment: In this assignment, you have learnt to implement the
solution for a simple real world problem using variables and operators
Summary of this assignment: In this assignment, you have learnt to implement the
solution for a simple real world problem using variables and operators
num = 16
num1 = num/6
num2 = num//6
num3 = num//6.0
print(num1)
print(num2);
print(num3)
Output:
2.6666666666666665
2
2.0
Problem Description:
Dry run the below code snippets and predict the output. You may want to confirm the
output by executing the code using Eclipse IDE.
Code – 1:
obj_x = 10
obj_y = obj_x
if ( id(obj_x) == id(obj_y) ):
print("Address of obj_x and obj_y is same")
else:
print("Address of obj_x and obj_y is not same")
Output:
Code – 2:
obj_x = 10
obj_y = obj_x
if ( obj_x is obj_y ):
print("obj_x and obj_y have same identity")
else:
print("obj_x and obj_y do not have same identity")
Output:
Code – 3:
obj_x = 10
obj_y = obj_x
obj_y = obj_x + 1
if ( obj_x is not obj_y ):
print("obj_x and obj_y do not have same identity")
else:
print("obj_x and obj_y have same identity")
Output:
Code – 4:
int_a = 10
raw_input = input("Enter a number")
print("Type of int_a:", type(int_a))
print("Type of raw_input:", type(raw_input))
print(int_a + raw_input)
Output:
Enter a number 6
Type of int_a: <class 'int'>
Type of raw_input: <class 'str'>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Problem Description: Coding standards are very important for maintenance of code and
for understanding of the code. Identify the sections of the given program where the coding
standards are not followed and correct them.
itemNo=1005
unitprice = 250
quantity = 2
amount=quantity*unitprice
print("Item No:",itemNo)
print("Bill Amount:",amount)
Summary of this assignment: In this assignment, you have learnt Python coding
standards
Summary of this assignment: In this assignment, you have understood the need of
operators and control structures using a real world problem
Problem Description: Suppose the retail store management now wants to provide 2%
discount for all bill amounts above Rs.500 and for all other bill amont, a discount of 1%.
Write a Python program to implement the same?
bill_id = 1001
customer_id = 101
bill_amount = 200.0
discounted_bill_amount = 0.0
print("Bill Id:%d" %bill_id)
print("Customer Id:%d" %customer_id)
Note the use if else statement
print("Bill Amount:Rs.%f" %bill_amount)
if bill_amount > 500:
discounted_bill_amount = bill_amount - bill_amount * 2 / 100
else:
discounted_bill_amount = bill_amount - bill_amount * 1 / 100
print("Discounted Bill Amount:Rs.%f" %discounted_bill_amount)
Output:
Bill Id:1001
Customer Id:101
Bill Amount:Rs.200.000000
Discounted Bill Amount:Rs.198.000000
Problem Description: Suppose the retail store management now wants to provide
discount for all bill amounts as mentioned below.
bill_id = 1001
customer_id = 101
bill_amount = 1200.0
discounted_bill_amount = 0.0
discount = 0
print("Bill Id: %d" %bill_id)
print("Customer Id: %d" %customer_id)
print("Bill Amount:Rs. %f" %bill_amount)
if bill_amount >= 1000:
Note the use of elif ladder
discount = 5
elif bill_amount >= 500:
discount = 2
else:
discount = 1
discounted_bill_amount = bill_amount - bill_amount * discount / 100
print("Discounted Bill Amount:Rs. %f" %discounted_bill_amount)
Output:
Problem Description: Suppose the retail store management now wants to provide
discount for all bill amounts as mentioned below.
For valid customers, discount must be provided as per the table given below:
bill_id = 1001
customer_id = 101
bill_amount = 200.0
discounted_bill_amount = 0.0
print("Bill Id: %d" %bill_id)
Note the usage of logical
print("Customer Id: %d" %customer_id) AND operator
print("Bill Amount:Rs. %f" %bill_amount)
Note the use of
if ((customer_id > 100) and (customer_id <= 1000)) is True:
nested if statement
if bill_amount >= 500:
discounted_bill_amount = bill_amount - bill_amount * 10 / 100
print("Discounted Bill Amount:Rs. %f" %discounted_bill_amount)
else:
Note the display of
print("No Discount")
appropriate error messages
else:
print("Invalid Customer id, customer id must between 101 and
1000")
Output:
Problem Description: Objective: Given a real world problem be able to understand the
need for control structures and operators to implement the logic and solve the problem
Note:
Employee Id must be considered as 1001,
Basic salary of the employee must be considered as Rs.15000.00 and
Allowances must be considered as Rs.6000.00
Write a Pseudo code and Python program in Eclipse to solve the above real world
problem.
Problem Description: Extend the program written for Assignment 15 to find the income
tax to be paid (In Indian Rupees) and the total salary after the income tax deduction as
per the details given in below table.
Note:
Employee Id must be considered as 1001,
Basic salary of the employee must be considered as Rs.15000.00 and
Allowances must be considered as Rs.6000.00
Write a Pseudo code and Python program in Eclipse to solve the above real world
problem.
Objective: Given a real world problem, implement the logic and solve the problem using
appropriate constructs (sequential, selection, iteration) using an object oriented
programming language (Python)
Problem Description:
Dry run the below code snippets and predict the output. You may want to confirm the
output by executing the code using Eclipse IDE.
Code – 1:
counter = 1
Output:
1
2
3
End of Program
Code-2:
Output:
Code-3:
number = 1
result = 0
while number < 5:
result = result + number
number = number + 1
print(result)
Output:
10
Code-4:
result = 0
for index in range(40, 10, -2):
if(index % 5 == 0):
result = result + index
print(result)
Output:
40
70
90
Code-5:
amount = 100.0
interest = 0.0
months = 1
while months < 6:
interest = amount * 0.2
amount = amount + interest
months += 1
print(amount)
Output:
248.83200000000002
Objective: Given a real world problem, implement the logic and solve the problem using
appropriate constructs (sequential, selection, iteration) using an object oriented
programming language (Python)
Problem Description:
Dry run the below code snippet and predict the output. You may want to confirm the output
by executing the code using Eclipse IDE.
Code:
count = 0
result = 0
for count in range (1, 10):
result = result + count
Note the use of break statement On encountering the
if result > 6: break statement,
break control will move out
print("Result =", result) of the loop as shown
here
Output:
Result = 10
Objective: Given a real world problem, implement the logic and solve the problem using
appropriate constructs (sequential, selection, iteration) using an object oriented
programming language (Python)
Problem Description:
Dry run the below code snippet and predict the output. You may want to confirm the output
by executing the code using Eclipse IDE.
Code:
Output:
0
1
2
3
5
6
7
8
9
Problem Description: The code given below is written to display all the even numbers
between 50 and 80 (both inclusive). Debug the program to get the correct output.
Step 1: Type the below program in Eclipse, save the file as for_loop.py, compile and
execute.
Step 2: Correct the logical error in the code, save, compile and execute the code
Step 3: Implement the same logic using while loop
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have learnt the implementation
of iteration control structure and break statement.
Strings - Assignments
Objective: Observe the need for features in the retail application scenario to correlate
the application of Strings
Problem Description: In the retail application, along with the earlier details included for
Customer, the retail shop wants to keep track of customer name. Customer name should
be between 3 and 20 characters.
Summary of this assignment: In this assignment, you have understood the need of
strings using a retail application scenario
Problem Description: In the retail application, along with the earlier details included for
Customer, the retail shop wants to keep track of customer name. Customer name should
be between 3 and 20 characters.
bill_id = 1001
customer_id = 1001
bill_amount = 2000
customer_name = Kevin
Code:
Output:
Please enter Bill id101
Please enter Customer id1001
Please enter bill Amount2000
Please enter Customer NameKevin
Bill Id: 101
Customer Id: 1001
Bill Amount:Rs. 2000
Customer Name: Kevin
Problem Description:
Assume,
string1 = “Infosys Limited”
string2 = “Mysore”
Q1: print(string1[:4])
Q2: print(string1[-1])
Q3: print(string1 * 2)
ANSWERS
Q1: Info
Q2: d
Q3: Infosys LimitedInfosys Limited
Q4: Infosys LimiteMysoreInfosys Limite
Q5: y
Q6: r
Q7: Infosys LimitedInfosys LimitedInfosys LimiteMysore
Summary of this assignment: In this assignment, you have revisited concepts of strings
through code snippets
Objective: Given a computational problem, be able to use the right data structures (lists
and strings) and implement the solution to the problem and test using a set of values in
an IDE
Problem Description:
a. Write a program to count and display the number of capital letters in a given string.
b. Write a program to check if the given string is Palindrome or not?
c. Write a program to count the number of each vowel in a string
d. Write a program to remove all punctuation from the string provided by the user
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''‘
Hint: Use membership operators IN, Not IN
Summary: In this assignment, you have understood the application and implementation
of Strings concept for the given computational problem.
Objective: Given a computational problem, be able to use the right data structures (lists
and strings) and implement the solution to the problem and test using a set of values in
an IDE
Problem Description: Write a Python program to accept a string and display the
resultant string in reverse order. The resultant string should contain all characters at the
even position of accepted string ignoring blank spaces.
accepted_string: An apple a day keeps the doctor away
resultant_string: Aapedyepteotrwy
expected_output: ywrtoetpeydepaA
Summary: In this assignment, you have understood the application and implementation
of Strings concept for the given computational problem.
Objective: Given a computational problem, be able to use the right data structures (lists
and strings) and implement the solution to the problem and test using a set of values in
an IDE
Problem Description: Given a string containing both upper and lower case letters. Write
a Python program to count the number of repeated characters and display the maximum
count of a character along with the character.
Sample Input: ABaBCbGc
Output:
2A
3B (three times B is repeated)
2C
1G
Summary: In this assignment, you have understood the application and implementation
of Strings concept for the given computational problem.
Objective: Given a computational problem, be able to use the right data structures (lists
and strings) and implement the solution to the problem and test using a set of values in
an IDE
Problem Description: Consider 2 strings string1 and string2 and display the
merged_string as the output. The merged_string should be capital letters from both the
strings in the order they appear.
Note: Each character should be checked if it is a capital letter and then it should be
merged.
Sample Input:
string1: I Like C
string2: Mary Likes Python
merged_string: ILCMLP
Summary: In this assignment, you have understood the application and implementation
of Strings concept for the given computational problem.
Objective: To understand the operations that can be performed on Tuples through a quiz
Problem Description:
Assume,
head = ("CEO",)
elements = ('Air', 'Water', 'Fire', 'Light', 'Land')
Q1: print(head)
Q2: print(elements)
Q2: print(elements[3])
Q3: elements[0]='Ice'
Q5: print(elements[-1])
Q6: print(elements[4])
Q7: print(elements[5])
ANSWERS
Q1: ('CEO',)
NOTE: In this case the symbol , is mandatory without which it becomes
just a string assignment operation
Q3: Light
Q5: Land
Q6: Land
Problem Description: Consider the list of courses opted by a Student “John” and
available electives as a part of Student Management System.
Summary of this assignment: In this assignment, you have learnt the implementation
of Tuple operations for given business scenario.
Lists - Assignments
Problem Description:
Assume,
language = ['Python']
languages = ['Python', 'C', 'C++', 'Java', 'Perl']
Q1: print(language)
Q2: print(languages)
Q3: print(languages[0:3])
Q4: print(languages[1:4])
Q5: print(languages[2])
Q6: print(languages[5])
Q7: print (languages[0] + " and " + languages[1] + " are quite
different!")
Q8: print ("Accessing the last element of the list: " + languages[-1])
ANSWERS
Q1: ['Python']
Q5: C++
Summary of this assignment: In this assignment, you have revisited concepts of lists
through code snippets
Objective: Given a computational problem, be able to use the right data structures (lists
and strings) and implement the solution to the problem and test using a set of values in
an IDE
Problem Description: Write a Python program to generate first ‘n’ Fibonacci numbers.
Store the generated Fibonacci numbers in a list and display it.
Sample input: Enter n 5
Sample Output: List: [0, 1, 1, 2, 3]
Summary: In this assignment, you have understood the application and implementation
of Lists concept for the given computational problem.
Problem Description: You have a bundle of currency of varied denominations. You want
to arrange them in descending order.
Given below is one approach to perform the above operation.
Write a Python program to sort the elements using bubble sort technique in the list and
display the elements in descending order.
Sample Input: [4, 1, 6, 2, 8, 5]
Sorted: [1, 2, 4, 5, 6, 8]
Output: [8, 6, 5, 4, 2, 1]
Summary: In this assignment, you have understood the application and implementation
of Lists concept for the given computational problem.
Objective: Given a computational problem, Implement the solution for the problem using
suitable data structures from an object oriented language (Python) using an IDE
Problem Description: ABC Retail Store sells different varieties of Furniture to the
customers. The list of furnitures available and its cost list are given below:
The furniture’s and its corresponding Cost should be stored as a list. If the required
furniture is available in list of furniture’s listed above and Quantity purchased is greater
than zero, only then bill amount should be calculated. In case of invalid values for furniture
required by the customer and quantity purchased, consider bill amount to be 0.
Initialize required furniture and required quantity with different values and test the results.
Write a Python program to calculate and display the bill amount to be paid by the customer
based on the furniture bought and quantity purchased.
Summary: In this assignment, you have understood the application and implementation
of Lists concept for the given computational problem.
Problem Description:
Q1: print(fruits)
Q6: print(len(fruit_basket))
Q9: print(fruits.issubset(fruit_basket))
Q10: print(fruits.issuperset(fruit_basket))
Q11: print(fruit_basket.copy())
ANSWERS
Q6: 5
Q7: True
Q8: True
Q9: False
Q10: False
Summary of this assignment: In this assignment, you have revisited concepts of Sets
through code snippets
Summary of this assignment: In this assignment, you have learnt the implementation
of Set operations for given business scenario.
Problem Description:
ANSWERS
a: print(customer_details)
b: print(len(customer_details))
c: print(sorted(customer_details.values()))
d: del(customer_details[1005])
print(customer_details)
e: customer_details[1003] = "Mary"
print(customer_details)
f: print(1002 in customer_details)
Summary of this assignment: In this assignment, you have learnt the implementation
of Dictionary operations for given business scenario.
Objective: Given a computational problem, select the right set of data structures (lists
and dictionary) and implement the solution to problem and test using a set of values in an
IDE
Summary: In this assignment, you have understood the application and implementation
of Dictionary concept for the given computational problem.
distance between Phoenix, Arizona and Salt Lake City, Utah in USA
distance between Phoenix, Arizona and Tampa, Florida in the US.
We want to compare the distances and check which one is far off from Phoenix, Arizona.
Provided below are codes written to solve the above problem using pass by reference
technique – using Required arguments and Keyword Arguments.
Code:
else:
print("Both locations are equidistance from Phoneix")
else:
print("Both locations are equidistance from Phoneix")
Summary of this assignment: In this assignment, you have learnt the implementation
of functions and parameter passing technique - pass by reference through keyword
arguments and reference arguments
Problem Description: At an airport, a traveler is allowed entry into the flight only if he
clears the following checks
i. Baggage Check
ii. Immigration Check
iii. Security Check
Implementation details
check_baggage (baggage_amount)
Check if baggage_amount is greater than or equal to 0 and less than or equal to 40.
If baggage_amount is VALID
o return TRUE
else
o return FALSE
check_immigration (expiry_year)
Check if expiry_year is greater than or equal to 2001 and less than or equal to 2025.
If expiry_year is VALID
o return TRUE
else
o return FALSE
check_security(noc_status):boolean
If noc_status is TRUE
o return TRUE
else
o return FALSE
traveler()
In traveler() function, initialize the traveler Id and traveler name and invoke the functions
check_baggage(), check_immigration() and check_security() by passing required
arguments. Refer the table below for values of arguments.
Variable Value
traveler_id 1001
traveler_name Jim
baggageAmount 35
expiryDate 2019
nocStatus true
Summary of this assignment: In this assignment, you have learnt pass by reference
technique
Problem Description:
There are many built-in String methods available in Python. Match each method to what
it does.
ANSWERS:
Summary of this assignment: In this assignment, you have revisited String built-in
functions through match the following.
Objective: Given a computational problem, select the right set of data structures (lists
and dictionary) and implement the solution to problem and test using a set of values in an
IDE
Problem Description: Consider the price list of various items in the Retail Store.
Customer John wants to know the
i) Price of Costliest item sold in Retail store
ii) Average price of items in the Retail store
iii) Display of item price list in increasing order
Implement the solution using user-defined and built-in functions to accomplish above
mentioned business requirement.
Code:
def price_max(item_price):
print("Price of Costliest item in the Retail Store:
",max(item_price))
def average_price(item_price):
total_price = 0
for i in item_price:
total_price += i
average_price = total_price/len(item_price)
print("Average Price of items in the Retail Store:
",average_price)
def display_sorted_price(item_price):
item_price.sort()
print("Item Price List in increasing order: ",item_price)
price_max(item_price)
average_price(item_price)
display_sorted_price(item_price)
Output:
Summary: In this assignment, you have understood the application and implementation
of Lists concept for the given computational problem.
Objective: Given a computational problem, implement the solution to the given problem
using exception handling.
Problem Description: Consider the customer ids of a customer in the Retail Store.
Customer id can be vary between 1001 to 1005. Store the customer id in a list and handle
appropriate exceptions for the following:
i) Store the customer id “1002” as string
ii) Print customerid[5]
Objective: Given a business scenario, able to identify the classes and objects
Problem Description:
A supermarket wants to automate the system of purchase of items by customers and the
billing process. The automation involves the maintenance of items, employees,
customers, purchase of items by customer and billing of items. Customers can be regular
visitors to the store in which case they are eligible for discounts based on the bill amount.
The customers can also be privileged ones, wherein they are given membership cards
(Platinum, Gold and Silver). Such customers are eligible for gifts based on the type of
membership card. The billing staff does the billing and delivery of items to the customer.
The bill calculation involves the logic of computation of the bill depending on customer
type. The customer can pay the bill through credit card or cash. In the former case, two
percent processing charge is applicable. Sales tax is also applicable on the final bill
amount. Employees in that supermarket can be permanent and temporary. Permanent
employees will get additional benefits in salary.
Questions
• Identify the classes.
• Identify the attributes / behaviors associated with each class.
Summary of this assignment: In this assignment, you have revisited object oriented
concepts using scenarios
2. Consider the following statement: “Vehicles can be of two types viz. Water vehicles
and Land vehicles “. Which OO concept may be used to represent this scenario?
3. As part of our family trip plan we went to Zoo. My son asked me lot of questions I
tried my level best to answer all of his questions. I showed him different types of
monkeys which were locked in different rooms. He asked me, “Dad, you said all
are monkeys then why they are kept in different rooms?” Now, which OO concept
may be used to represent this scenario?
Summary of this assignment: In this assignment, you have revisited object oriented
concepts using scenarios
Summary of this assignment: In this assignment, you have revisited object oriented
concepts using simple true/false questions
Objective: Given a business scenario, be able to identify the components of a use case
diagram
Problem Description: Refer to the course registration system case study and answer
the following questions.
distance of travel. Yearly hostel fees are applicable for all the hostelites. Yearly
infrastructure fees and library fees are also applicable to all the students. Admin
calculates the yearly college fees for each student and the college fees include all the
fees specified earlier based on the type of student. Admin will provide a printed receipt of
the fees to the students once the annual college fees have been paid.
At the time of registration, student has to provide the permanent address and in case the
student is opting to be a day scholar, he/she has to provide the residential address also.
Assumption:
1. Decision of the branch of study a student is allocated, is not within the scope of
this case study
Questions:
Summary of this assignment: In this assignment, you have learnt how to actors and
activities of a use case diagram using a course registration system scenario
Problem Description: In the retail application, there are many customers who visit the
retail outlet to purchase various items. The manager of the retail outlet now wants to keep
track of all its customers’ data. Let us assume that customer details include Customer Id
and Telephone Number.
For the class diagram identified in OO Fundamentals, implement the class using Eclipse
IDE and execute it by writing a starter class.
Code: Execute the code using Eclipse IDE with the given inputs and understand the
following:
• Access Specifiers
• Variables – Local and Instance variables
• Methods
• Starter class
• Creation of objects
• Reference variables
• Compilation and Execution of a python program
Problem Description: Let us revisit the class diagram drawn and implemented for
Customer class as part of Object Oriented Fundamentals.
Class diagram:
Customer
-customerid : int
-telephoneno : long
+setcustomerid(int) : void
+getcustomerid() : int
+settelephoneno(long) : void
+gettelephoneno() : long
Code:
Execute the code using Eclipse IDE with the given inputs and observe the results.
class Customer:
def setcustomerid(self, customerid):
customerid = customerid
def getcustomerid(self):
return customerid
def gettelephoneno(self):
return telephoneno
custobj = Customer()
custobj.setcustomerid(1001)
custobj.settelephoneno(9201861311)
print("Customer Id : ", custobj.getcustomerid())
print("Telephone No : ", custobj.gettelephoneno())
Note: Without ‘self’, it will be considered as normal local variable and that will be removed at the end of
the scope of method. Hence, it is not possible to access it from outside of the method where it is defined.
def gettelephoneno(self):
return self.telephoneno
custobj = Customer()
custobj.setcustomerid(1001)
custobj.settelephoneno(9201861311)
print("Customer Id : ", custobj.getcustomerid())
print("Telephone No : ", custobj.gettelephoneno())
Output:
Customer Id: 1001
Telephone No: 9201861311
Note: “self” is not a keyword and has no special meaning in Python. We can use any name in that
place. However, it is recommended not to use any name other than “self” (merely a convention and for
readability)
Summary of this assignment: In this assignment, you have learnt the usage of self
reference for accessing the instance variables using a retail application scenario
Objective: Observe the need for features in the retail application scenario to correlate
the application of initializing the members and ‘static’ members
Class diagram:
Customer
-customerid : int
-telephoneno : long[]
-customername : String
+ setcustomerid(int) : void
+getcustomerid() : int
+settelephoneno(long[]) : void
+gettelephoneno() : long[]
+setcustomername(String) : void
+getcustomername() : String
+validatecustomername() : boolean
Code:
Execute the code using Eclipse IDE with the given inputs and observe the results.
class Customer: Note that since we have not explicitly coded
def setcustomerid(self, id): the __init()__ method, system will not initialize
the instance variables to their default values
Version No: 1.0 Page 51 of 79
Infosys Limited Assignments for Programming in Python
self.__customerid = id
def getcustomerid(self):
return self.__customerid
def gettelephoneno(self):
return self.__telephoneno
def getcustomername(self):
return self.__customername
def validatecustomername(self):
if(len(self.__customername)>=3 and len(self.__customername)
<=20):
return True
else:
return False
custobj = Customer()
print("Customer Id : ", custobj.getcustomerid())
print("Telephone Nos : ", custobj.gettelephoneno())
print("Customer Name : ", custobj.getcustomername())
Output:
Traceback (most recent call last):
File "D:/****/Assignment9.py", line 27, in <module>
print("Customer Id : ", custobj.getcustomerid())
File "D:/****/Assignment9.py", line 12, in getcustomerid
return self.__customerid
AttributeError: 'Customer' object has no attribute '_Customer__customerid'
Revised Code: The code above has been revised by adding __init__() method
class Customer:
def __init__(self):
self.__customerid=0
self.__customername=None
self.__telephoneno=[]
def getcustomerid(self):
return self.__customerid
def gettelephoneno(self):
return self.__telephoneno
def getcustomername(self):
return self.__customername
def validatecustomername(self):
if(len(self.__customername)>=3 and len(self.__customername)
<=20):
return True
else:
return False
custobj = Customer()
print("Customer Id : ", custobj.getcustomerid())
print("Telephone Nos : ", custobj.gettelephoneno())
print("Customer Name : ", custobj.getcustomername())
Output:
Customer Id : 0
Telephone Nos : []
Customer Name : None
No…Values initialized for each customer must be different. It depends on each customer.
This can be achieved using parameterized __init__()
Revised Code 2: The code above has been revised by adding parameterized __init__()
method
class Customer:
def __init__(self, customerid, telephoneno, customername):
self.__customerid=customerid
self.__customername=customername
self.__telephoneno=telephoneno
def getcustomerid(self):
return self.__customerid
def gettelephoneno(self):
return self.__telephoneno
def getcustomername(self):
return self.__customername
def validatecustomername(self):
if(len(self.__customername)>=3 and len(self.__customername)
<=20):
return True
else:
return False
Output:
Customer Id : 1001
Telephone Nos : 9201861311 , 9201861321 , 9201661311
Customer Name : Kevin
The class diagram discussed in Object Oriented Fundamentals Assignment 51 has been
modified as shown below.
Class diagram:
Customer
-customerid : int
-telephoneno : long[]
-customername : String
+ Customer(int, long[], String)
+ setcustomerid(int) : void
+getcustomerid() : int
+settelephoneno(long[]) : void
+gettelephoneno() : long[]
+setcustomername(String) : void
+getcustomername() : String
+validatecustomername() : boolean
Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Customer:
def __init__(self, customerid, telephoneno, customername):
self.__customerid=customerid
self.__customername=customername Note how parameterized __init__()
self.__telephoneno=telephoneno method is written
def getcustomerid(self):
return self.__customerid
def gettelephoneno(self):
return self.__telephoneno
def getcustomername(self):
return self.__customername
def validatecustomername(self):
if(len(self.__customername)>=3 and len(self.__customername)
<=20):
return True
else: Note how parameterized
return False __init__() method is
invoked
telephoneno=[9201861311, 9201861321, 9201661311]
custobj = Customer(1001, telephoneno, "Kevin")
if(custobj.validatecustomername()):
print("Customer Id : ", custobj.getcustomerid())
temp = custobj.gettelephoneno()
print("Telephone Nos : ", temp[0], ",", temp[1], ",", temp[2])
print("Customer Name : ", custobj.getcustomername())
else:
print("Invalid customer name. Customer name must be between 3 and
20 characters")
Output:
Customer Id:1001
Telephone Nos:9201861311, 9201861321, 9201661311
Estimated time: 15 minutes
Customer Name:Kevin
Note: Few instance variables are not shown in the class diagram so as to keep the code
simple to understand.
Class diagram:
Customer
-customerid : int
+Customer()
+setcustomerid(int) : void
+getcustomerid() : int
+totalnoofcustomers() : int
Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Customer:
def __init__(self, cid=1000):
self.__customerid=cid+1
def getcustomerid(self):
return self.__customerid
def totalcustomers(self):
return 0
objcust = Customer()
print("Customer Id: ", objcust.getcustomerid())
objcust2 = Customer()
print("Customer Id: ", objcust2.getcustomerid())
Output:
Why do you think customer id is
Customer Id:1001 not auto incremented for each
customer?
Customer Id: 1001
customerId is an instance variable of Customer class and it will be created separately for each and every
object of Customer class. Hence each time an object of Customer class is created, constructor is called
and customerId will be initialized to 1000 and will be incremented by 1 in the constructor as a result for all
the objects customerId will remain as 1001. Hence we need to have a variable common to all the objects
of Customer class
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Customer:
counter = 1000 Note how the class/static variable is
def __init__(self): created for the class
Customer.counter = Customer.counter+1
self.__customerid=Customer.counter
Note how the class/static variable is
def setcustomerid(self, cid): accessed
self.__customerid=cid
def getcustomerid(self):
return self.__customerid
Note the use of @staticmethod to
convert a method into static one
@staticmethod
def totalcustomers(): “self” argument is not needed for
return Customer.counter-1000 static method
objcust = Customer()
print("Customer Id: ", objcust.getcustomerid())
objcust2 = Customer()
print("Customer Id: ", objcust2.getcustomerid()) Note the different ways of invoking
the static methods in the class.
print("Total Customers: ", objcust.totalcustomers())
print("Total Customers: ", objcust2.totalcustomers())
print("Total Customers: ", Customer.totalcustomers())
Output:
Customer Id: time:
Estimated 1001 20 minutes
Customer Id: 1002
Total Customers: 2
Total Customers: 2
Total Customers: 2
Problem Description: The Retail Store has the requirement for printing many reports
including the bill. All reports contain header. The header may be
Summary of this assignment: In this assignment, you have understood the need of
method overloading using a retail application scenario
Objective: Given a class diagram for a use case representing a computational problem,
use method and constructor overloading techniques to solve the problem and test using
a set of values in an IDE
A new class called PrintDetails with overloaded methods have to be created as shown
below:
Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
Note how default arguments are
class PrintDetails: used to bring method overloading
def printheader(self, c='*', no=1): equivalent in printHeader()
print(c * no)
obj = PrintDetails()
obj.printheader('#', 10)
obj.printheader("Report")
obj.printheader('#' ,10)
obj.printheader()
Output:
##########
Report
##########
Estimated time: 10 minutes
*
Summary of this assignment: In this assignment, you have learnt the need and
implementation of method with default parameters using a retail application scenario.
Objective: Observe the need for features in the retail application scenario to correlate
the application of relationships concept
Problem Description:
1. The retail shop has two types of customers, Regular and Privileged.
Regular customers are entitled to get some discount on each purchase apart from having all the
properties of a customer. On the other hand, privileged customers hold membership card – Platinum,
Gold or Silver based on which they receive gifts on each purchase. This is in addition to having all the
properties of a customer. Thus in this case, Customer is the generalized case and Regular and
Privileged customer are the specialized cases of Customer. This relationship is known as “is-a”
relationship and can be represented using class diagram as shown below:
is-a relationship
2. The retail store management wants to keep track of the address of every customer so
as to allow for home delivery at a later point of time.
a. How many fields represent the address?
b. Do you think address qualifies to be a class?
c. What do you think is the relationship between Customer and Address?
d. How can this relationship be represented using class diagram?
Address can be considered as a separate class since the same class if required can be reused at a
later point of time. For example, if retail store needs to keep track of its employees address, the same
address class can be reused. The relationship between Customer class and Address class will be “Has
–A” relationship since every customer has an address. This relationship can be represented using
class diagram as shown below:
As stated, PrintDetails class contains methods which can be used to display the bill in the required
format. Hence the relationship between PurchaseBill and PrintDetails class is “uses-a” relationship.
This relationship can be represented using class diagram as shown below:
Summary of this assignment: In this assignment, you have understood the need of
relationships and its representation using a retail application scenario
Objective: Given a class diagram for a use case representing a computational problem,
implement inheritance (single level, multilevel and hierarchical) to solve the problem,
trace the flow of the program between the base and derived classes and test using a
set of values in an IDE and recognize the benefits of inheritance
Problem Description: In the retail application, we have already seen that customers are
of two types – Regular and Privileged. Regular customers are entitled for discount on
each purchase and Privileged customers hold membership cards – Platinum, Gold or
Silver based on which they are entitled to get gifts on each purchase.
The class diagram presented to you as part of OO Concepts Part I Assignment 5 has
been modified to represent the inheritance relationship.
Note: Few instance variables and methods are not shown in the class diagram so as to
keep the code simple to understand.
Class diagram:
Customer
-customerid : int
-customername : String
+setcustomerid(int) : void
+setcustomername(String) : void
+getcustomerid() : int
+getcustomername() : String
RegularCustomer PrivilegedCustomer
- discount : float - memCardType : String
+setdiscount(float) : void +setmemcardtype(String) : void
+getdiscount () :float +getmemcardtype() :String
Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
Note that both RegularCustomer
class Customer: and PrivilegedCustomer are having
def setcustomerid(self, id): Customer as the parent class, hence
self.__customerid = id this is an example of hierarchical
inheritance
def setcustomername(self, name):
self.__customername=name
def getcustomerid(self):
return self.__customerid
def getcustomername(self):
return self.__customername
class RegularCustomer(Customer):
def setdiscount(self, dis):
self.__discount=dis
def getdiscount(self):
return self.__discount
class PrivilegedCustomer(Customer):
def getmemcardtype(self):
return self.__memcardtype
objr = RegularCustomer()
objr.setcustomerid(1001)
objr.setcustomername('Ram')
objr.setdiscount(10.0)
print("Regular Customer Details")
print("Customer Id: ", objr.getcustomerid())
print("Customer Name: ", objr.getcustomername())
print("Discount Eligible: ", objr.getdiscount())
print("*********")
objp = PrivilegedCustomer()
objp.setcustomerid(1002)
objp.setcustomername("Seetha")
objp.setmemcardtype("Gold")
print("Regular Customer Details")
print("Customer Id: ", objp.getcustomerid())
print("Customer Name: ", objp.getcustomername())
print("Discount Eligible: ", objp.getmemcardtype())
Output:
Regular Customer Details
Customer Id: 1001
Customer Name: Ram
Discount Eligible: 10.0
********* How can the instance variables
Regular Customer Details be initialized along with object
Customer Id: 1002 creation??
Customer Name: Seetha
Discount Eligible: Gold
Revised Code:
class Customer:
def __init__(self, id=0, name=None):
self.__customerid=id
self.__customername=name
def getcustomerid(self):
return self.__customerid
def getcustomername(self):
return self.__customername
class RegularCustomer(Customer):
def __init__(self, id=0, name=None, dis=0):
super().__init__(id,name)
self.__discount=dis
def getdiscount(self):
return self.__discount
class PrivilegedCustomer(Customer):
def __init__(self, id=0, name=None, card=None):
super().__init__(id,name)
self.__memcardtype=card
def getmemcardtype(self):
return self.__memcardtype
objr = RegularCustomer()
print("Regular Customer Details")
print("Customer Id: ", objr.getcustomerid())
print("Customer Name: ", objr.getcustomername())
print("Discount Eligible: ", objr.getdiscount())
print("*********")
objp = PrivilegedCustomer()
print("Regular Customer Details")
print("Customer Id: ", objp.getcustomerid())
print("Customer Name: ", objp.getcustomername())
print("Discount Eligible: ", objp.getmemcardtype())
print("*********")
objr = RegularCustomer()
objr.setcustomerid(1001)
objr.setcustomername('Ram')
objr.setdiscount(10.0)
print("Regular Customer Details")
print("Customer Id: ", objr.getcustomerid())
print("Customer Name: ", objr.getcustomername())
print("Discount Eligible: ", objr.getdiscount())
print("*********")
objp = PrivilegedCustomer()
objp.setcustomerid(1002)
objp.setcustomername("Seetha")
objp.setmemcardtype("Gold")
print("Regular Customer Details")
print("Customer Id: ", objp.getcustomerid())
print("Customer Name: ", objp.getcustomername())
print("Discount Eligible: ", objp.getmemcardtype())
Output:
Regular Customer Details
Customer Id: 0
Customer Name: None
Discount Eligible: 0
*********
Regular Customer Details
Customer
Version No: Id:
1.0 0 Page 67 of 79
Customer Name: None
Discount Eligible: None
*********
Infosys Limited Assignments for Programming in Python
class Derived(Base):
def __init__(self):
print("Derived init invoked")
obj = Derived()
class Base:
def __init__(self, v):
self.baseVar = v
self.var=0
print("Base Class init invoked")
class Der(Base):
def __init__(self, v):
super().__init__(v)
self.derVar=v
self.var=0
print("Derived class init invoked")
def display(self):
print("Base variable value: ", self.baseVar)
print("Derived variable value: ", self.derVar)
def useOfSuper(self):
self.var=15
print("Base Variable Value -> ", Base.var)
print("Derived Variable Value -> ", self.var)
d = Der(10)
d.display()
d.useOfSuper()
class Base:
def __init__(self, v):
self.baseVar = v
print("Base Class init invoked")
class Der(Base):
def __init__(self, v):
self.derVar=v
print("Derived class init invoked")
def display(self):
print("Base variable value: ", self.baseVar)
print("Derived variable value: ", self.derVar)
d = Der(10)
d.display()
class Base:
def __init__(self, v):
self.baseVar = v
print("Base Class init invoked")
class Der(Base):
def __init__(self, v):
self.derVar=v
print("Derived class init invoked")
def display(self):
print("Base variable value: ", self.baseVar)
print("Derived variable value: ", self.derVar)
d = Der(10)
d.display()
ANSWERS
Q1.
Derived init invoked
Q2.
Runtime Error: This is because the data members of the base class can’t be overridden
by the derived class as the members are added to object during initialization and not to
the class. Hence, the error message “type object 'Base' has no attribute 'var'”
Q3.
Derived class init invoked
AttributeError: 'Der' object has no attribute 'baseVar'
Q4.
Runtime Error: This is because, when the object of derived class is made, there is no
explicit invocation of the base class __init__() and hence the baseVar is not initialized,
means that base class doesn’t have any data member. Hence, when the display is
invoked triggers an error while trying to print the Base class variable, which is not
available.
Q5.
a)False
b)True
c)False
d)False
Objective: Given a class diagram for a use case representing a computational problem,
implement has-a and uses-a relationships to solve the problem and test using a set of
values in an IDE and recognize the benefits of the mentioned relationships
Problem Description: In the retail application, we have already seen that every customer
has an address. Address consists of address line, city, state and zipcode.
Note: Few instance variables and methods are not shown in the class diagram so as to
keep the code simple to understand. Similarly, regular and privileged customer classes
are also not shown here.
Class diagram:
Customer Address
-customerid : int -addressline : string
-address : Address -city : string
-counter : int -> static -zip : string
+Customer(Address) -state : string
+getcustomerid() : int +Address(string, string, string, string)
+getaddress() : Address +setaddressline(string) : void
+setcity(string) : void
+setzip(string) : void
+setstate(string) : void
+getaddressline() : string
+getcity() : string
+getzip() : string
+getstate() : string
Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Address:
def __init__(self, addressline, city, state, zip):
self.__addressline = addressline
self.__city=city
self.__state=state
self.__zip=zip
def getaddressline(self):
return self.__addressline
def getcity(self):
return self.__city
def getstate(self):
return self.__state
def getzip(self):
return self.__zip
class Customer:
def __init__(self, cid, address):
self.__customerid = cid
self.__address = address
def getcustomerid(self):
return self.__customerid
def getaddress(self):
return self.__address
Output:
Customer Id: 1001
Customer Address: No.333,Oak street , Strathfield , New South Wales , 570018
In this example, Address reference is passed to the __init() of Customer class. Since it is a reference of
an object that is passed, the parameter passing technique used is pass by referene.
Objective: Given a class diagram for a use case representing a computational problem,
implement has-a and uses-a relationships to solve the problem and test using a set of
values in an IDE and recognize the benefits of the mentioned relationships
Problem Description: In the retail application, we have already seen that purchase bill
has to be created in a particular format.
Note: Few instance variables and methods are not shown in the class diagram so as to
keep the code simple to understand.
Class diagram:
PurchaseBill
-billId: int
-billAmount:double
-counter: int->static
+PurchaseBill(double)
+getBillId(): int
+getBillAmount():double
+calculateBill(String,int): void
+displayBill(): void
Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results. Few changes are made to PurchaseBill class, the changes are
highlighted in the code below:
class PrintDetails:
def printheader(self, c, no=1):
print(c*no)
class PurchaseBill:
def __init__(self, bid, billamount):
self.__billid = bid
self.__billamount = billamount
def getbillid(self):
return self.__billid
def getbillamount(self):
return self.__billamount
def displaybill(self):
objprint = PrintDetails()
objprint.printheader("-", 80)
objprint.printheader(" Easy Shop Retail Store
Bill ")
objprint.printheader("-", 80)
print("Bill Id: ", self.__billid)
print("Final amount to be paid: Rs.", self.__billamount)
objprint.printheader("-", 80)
objprint.printheader(" Thank You!!!
")
objprint.printheader("-", 80)
Execute the above code using the following values for command line arguments
Case – 1:
Arguments to be passed – “Cash” and 0
Case –1 Output:
--------------------------------------------------------------------------------
Easy Shop Retail Store Bill
--------------------------------------------------------------------------------
Bill Id: 101
Final amount to be paid: Rs. 1055.0
--------------------------------------------------------------------------------
Thank You!!!
--------------------------------------------------------------------------------
Case – 2:
Arguments to be passed – “Credit” and 5
Case – 2 Output:
--------------------------------------------------------------------------------
Easy Shop Retail Store Bill
--------------------------------------------------------------------------------
Bill Id: 101
Final amount to be paid: Rs. 1107.75
--------------------------------------------------------------------------------
Thank You!!!
--------------------------------------------------------------------------------
class customer:
counter = 1000 #class variable
def __init__(self, telephoneno, customername, add):
customer.counter += 1
self.__customerid=customer.counter
self.__customername=customername
self.__telephoneno=telephoneno
self.__address = add
def getcustomerid(self):
return self.__customerid
def gettelephoneno(self):
return self.__telephoneno
def getcustomername(self):
return self.__customername
def getaddress(self):
return self.__address
@staticmethod
def gettotalcustomer():
return customer.counter-1000
class regularcustomer(customer):
def getdiscount(self):
return self.__discount
class address:
def __init__(self, add):
self.__addressline = add
def getaddress(self):
return self.__addressline
print("\n")
regcustadd2 = address("No.33,J.P. Nagar Bangalore Karnataka 570011")
teleno1 = [1122334455, 1199887766, 2244668897]
regcustobj2 = regularcustomer(teleno1, "Mary", 15.5,regcustadd2)
print("Customer id:", regcustobj2.getcustomerid())
print("Telephone no:", regcustobj2.gettelephoneno())
Output:
Customer id: 1001
Telephone no: [9201861311, 9201861321, 9201661311]
Customer name: John
Discount: 12.5
Customer's address: No.22,Vijay Nagar Mysore Karnataka 570018