Tech 501 - 515 - Python - SH
Tech 501 - 515 - Python - SH
2
TECH 501 - INTRODUCTION TO PYTHON,OPERATORS
THEORY CONCEPTS:
1. Intro to Python
2. Data types
3. I/O statements
4. Operators - Arithmetic Operators, Assignment Operators, Relational Operators,
Logical Operators, Bitwise Operators, Membership Operators, Identity Operators
PROGRAM 1
Once upon a time in the city of Mysore, there lived a young programmer named Arjun. He
was known for curiosity in solving problems with creative coding solutions. One day, Arjun
received an urgent message from the town's mayor. The problem was simple yet crucial: the
system needed to handle book IDs entered by librarians as integers but store them as floats for
better data management and future scalability. Determined to help, Arjun ensured that each
book ID was correctly converted and stored.
Sample Input:
55
Sample Output:
55.0
3
PROGRAM 2
In the enchanted village, there lived a brilliant coder named Samara. She was known for her
talent in weaving spells with her code, solving problems that seemed almost impossible to
others. Accepting the challenge, Samara set up her coding station under the village's great
wisdom tree, where the air was filled with the whispers of past knowledge. She knew she had
to write a script that could take a string input, convert it into an integer, and then display both
the original string and the converted integer for validation.
Sample Input:
12345
Sample Output:
12345
4
PROGRAM 3
Swap the values of two variables using the operators. Print the values before and after the
swap.
Sample Input:
35
55
Sample Output:
Before Swapping:
35
55
After Swapping:
55
35
Five ways!
5
TECH 502 - CONDITIONAL STATEMENTS
THEORY CONCEPTS:
1. Control Statements, Conditional Statements - if, if-elif and Nested if-elif-else
PROGRAM 1
Rainfall is classified as per the table below.
No Rain 0-1
Write a program to display the rainfall status based on the above information
Input Format
Rainfall (one hour category)
Output Format
Classification of rainfall based on given information
6
PROGRAM 2
John's little brother is struggling with Maths. He decided to design a calculator with basic
operations such as Addition, Subtraction, Multiplication and Division. The calculator should
input two float numbers and an operator from the user. It should perform an operation
according to the operator entered and must take input in a given format.
Input Format
The first line contains 2 float numbers separated by spaces.
The second line contains an operator which is going to perform on those inputs.
Output Format
Print the output
Sample Input:
20 8
+
Sample Output:
28.0
7
PROGRAM 3
Chocolate Game
It was Christmas Eve and the celebrations remembering the birth of Jesus were going on in
full swing at the Cathedral Chapel. The Event Management Team had arranged for some
exciting games after the mass worship and feast, where adults and kids of all ages participated
very actively. "Chocolate Game" was organized for the kids which involved a standard
chocolate of n by m pieces. More formally, chocolate is a rectangular plate consisting of n
rows and m columns. Two kids at a moment will play with the chocolate. First kid takes the
chocolate and cuts it into two parts by making either a horizontal or vertical cut. Then, the
second kid takes one of the available pieces and divides into two parts by either making a
horizontal or vertical cut. Then the turn of rst kid comes and he can pick any block of the
available chocolates and do the same thing again. The player who cannot make a turn loses.
Write a program to find which of the kids will win if both of them play optimally. Output
"Yes", if the kid who plays first will win, otherwise print "No".
Input Format
The only line of the input contains two space separated integers n and m - the sizes of the
chocolate.
Output Format
Output a single line containing one word "Yes" (without quotes) if there is a sequence of
moves leading to the winning of the person who moves first and "No" (without quotes)
otherwise.
Refer sample input and output for formatting specifications.
8
PROGRAM 4
The KG theatre in the city is newly renovated. So, they decided to give a 20% discount if one
person buys more than 15 tickets. Also,they give an extra 5% discount, if he/she is a student.
There won't be any discount if anyone purchases less than 15 tickets. The ticket rate may vary
based on the movie. Karthik has planned to book the tickets for his juniors and friends. Help
Karthick to calculate the amount and display whether the discount is applied or not.
Input Format
Ticket rate in first line
Number of tickets in second line
Category in third line
Output Format
Discount details in first line
Total amount in second line
(Refer sample outputs for exact text and format)
Sample Input
100
20
1
Sample Output
Discounts Applied - Maximum Tickets and Student
Total Amount - 1500.00
9
PROGRAM 5
An automobile company manufactures both a two wheeler (TW) and a four wheeler (FW). A
company manager wants to make the production of both types of vehicle according to the
given data below:
1st data, Total number of vehicle (two-wheeler + four-wheeler)=v
2nd data, Total number of wheels = W
The task is to find how many two-wheelers as well as four-wheelers need to manufacture as
per the given data.
Input format:
The candidate has to write the code to accept two positive numbers separated by a new line.
First Input line – Accept value of V.
Second Input line- Accept value for W.
Output format:
Written program code should generate two outputs, each separated by a single space character
Constraints :
2<=W
W%2=0
V<W
Print “INVALID INPUT” , if inputs did not meet the constraints.
Example :
Sample Input
200 -> Value of V
540 -> Value of W
Sample Output
TW =130 FW=70
Explanation:
130+70 = 200 vehicles
(70*4)+(130*2)= 540 wheels
10
TECH 503 - LOOPING STATEMENTS
THEORY CONCEPTS:
1. Iterative Statements - for , while
2. Pattern Programs using for loops
PROGRAM 1
A supermarket maintains a pricing format for all its products. A value N is printed on each
product. When the scanner reads the value N on the item, the product of all the digits in the
value N is the price of the item. The task here is to design the software such that given the
code of any item N the product (multiplication) of all the digits of value should be
computed(price).
Example 1:
Input :
5244 -> Value of N
Output :
160 -> Price
Explanation:
From the input above
Product of the digits 5,2,4,4
5*2*4*4= 160
Hence, output is 160.
11
PROGRAM 2
A Person invests some amount in a savings account yielding 5% interest. Assuming that all
interest is left on deposit in the account, calculate and print the amount of money in the
account at the end of each year for 10 years.
Use the following formula for determining these amounts:
a=p(1+r)n
Where
p is Original amount invested(user input)
r is annual interest rate (5%)
n is the number of years(10 Years)
a is the amount on deposit at the end of the nth
year.
Refer Sample input and output
Input Format
Amount to be deposited in account
Output Format
Amount at the end of every year for 10 years as shown in sample output
Sample Input
1000
Sample Output
1050.00
1102.50
1157.62
1215.51
1276.28
1340.10
1407.11
1477.46
1551.33
1628.89
12
PROGRAM 3
Jennie is working in a bank and her daily task is to guide the customers to all various bank
challans. As part of this, customers need to write the numbers in word format. Jennie decided
to write a program to read the number and print the number digit by digit in word format.
Help Jennie to complete this task.
Input Format
Number
Output Format
Given number in word format
Sample Input
659803
Sample Output
six five nine eight zero three
13
PROGRAM 4
Check if a car number plate is a fancy number or not. You consider a number as a fancy
number if the digits are continuous either continuous, increasing or decreasing numbers.
(Ex.1234, 7654 are fancy and 7765 is not fancy)
Input Format
Four digit number in first line
Output Format
Fancy number type
(Refer sample output for statement and format )
Constraints
Number should not more than four digits
Sample Input
1234
Sample Output
Increasing fancy number
Sample Input
7654
Sample Output
Decreasing fancy number
Sample Input
1256
Sample Output
Not fancy number
14
TECH 504 - STRINGS
THEORY CONCEPTS:
1. Strings
2. String functions
PROGRAM 1
A studzone website accepts its password(a string) if and only if its 5th Character is a number
from 1 to 5 and there must not be any whitespace characters in between. Write code to check
whether a given string is a valid password or not. Make use of isdigit and isspace inbuilt
functions.
Input Format
Password as String
Output Format
Print valid or invalid along with password
15
PROGRAM 2
Renu, a student, has been tasked with analyzing her notes for a class project. She decided to
write down a sentence and count the number of words in it. However, she often includes extra
spaces or punctuation, which makes counting tricky. Renu needs a program that can
accurately count the words in her sentence, ignoring any irregular spacing.
Input Format
The input consists of a sentence in which the words are separated by space
Output Format
The output prints the number of words in the sentence.
16
PROGRAM 3
Sethu is a cybersecurity enthusiast who wants to store his passwords securely. To achieve this,
he encrypts his passwords using a specific substitution scheme:
Replace every A with B.
Replace every a with @.
Replace every 1 with 2.
Keep all special characters and other characters unchanged.He needs a program to automate
this encryption process for any given password.
Input Format
The input consist of a string with mixture of alphabets,special characters and numbers
Output Format
The output prints the encrypted string with mixture of alphabets,special characters and
numbers
17
PROGRAM 4
Geetha, the English teacher, was teaching about the articles in English grammar. She decided
to play a game with the students in which a phrase or a sentence will be provided to the
students, and they should rewrite the given sentence after removing all the articles wherever
they may be present.
Write a program to find the correct answer for each sentence she provides.
Articles are ' a ' , ' an ', and ' the ' .
Input Format
Input is in the format of a string (character array).
Output Format
Output is the input string in which all the articles are removed.
Sample Input
The Dhillon Theatre is a Fun Republic or a mall.
Sample Output
Dhillon tre is Fun Republic or mll.
18
ADDITIONAL QUESTIONS:
PROGRAM 5
A tech startup is working on a unique feature for their mobile application. The app allows
users to create personalized messages by encoding and reversing the halves of words or
phrases. The goal is to provide an engaging way to share messages with friends by
scrambling parts of them.
To make the app more fun, they want a feature that allows users to split their input message
into two halves, reverse each half, and then combine them. This will give the message a new
twist, making it more interactive.
Input Format
String in first line
Output Format
Output the string after reversed.
19
TECH 505 - LIST & TUPLE DATA STRUCTURE
THEORY CONCEPTS:
1. Creating and accessing lists
2. List methods and operations
PROGRAM 1
Ramu is developing a data analysis tool for a company that processes user feedback scores.
The scores are stored in a list and can be either even or odd numbers.
Your task is to help him write a Python function to count how many scores are even and how
many are odd.
Sample Input:
Enter numbers separated by spaces: 1 2 3 4 5 6
Sample Output:
Even numbers: 3
Odd numbers: 3
20
PROGRAM 2
Lithin is a data analyst creating a tool for an e-commerce platform. The platform collects data
on how many times products are viewed by users. The view counts for various products are
stored in a list, where each product's ID appears as many times as it was viewed.
Your task is to identify the products that have been viewed more than a given number of times
k. Write a Python program that takes the list of product view counts and the value of k as
input, and prints the IDs of products that meet this criterion along with their frequencies.
Sample Input:
Enter the list of product IDs: 1 2 1 2 1 3 5 3 3
Enter the threshold value k: 2
Sample Output:
Products with frequency greater than 2 :
Product ID 1: 3 times
Product ID 3: 3 times
21
PROGRAM 3
Yashwanth is developing a data processing tool for a logistics company. They track deliveries
in a list of tuples, where each tuple contains information about a delivery (e.g., delivery ID,
weight, and cost). Your task is to calculate the product of all values in a specific column (e.g.,
weight or cost) based on the user's input for the column index (k).
Write a Python program that computes the product of all values in the k-th column of a given
list of tuples.
Sample Input:
Enter the list of tuples: (1, 2, 3), (4, 5, 6), (7, 8, 9)
Enter the column index (k): 1
Sample Output:
Product of values in column 1: 80
22
PROGRAM 4
The State Central Library is building a database management system. The library tracks the
books using a tuple of information such as the book's ID, title, author, and publication year.
You need to ensure that the books in the database have unique IDs. Write a Python program to
check if the IDs of the books in a given list are distinct. If there are duplicate IDs, the system
should flag the entry as invalid.
Sample Input:
Enter the list of book IDs (space-separated): 101 102 103 104 105
Sample Output:
The book IDs are distinct (no duplicates).
23
ADDITIONAL QUESTIONS:
PROGRAM 5
You are building a data-cleaning module for an analytics company. The module processes
lists of tuples that may contain invalid data represented as None. Your task is to write a
program that removes all tuples where every element is None to ensure only meaningful data
is processed.
Sample Input:
List of tuples: [(None, None), (1, 2), (None, 3), (None, None, None), (4, None)]
Sample Output:
Cleaned list: [(1, 2), (None, 3), (4, None)]
24
TECH 506 - SET AND DICTIONARY DATA STRUCTURE
THEORY CONCEPTS:
1. Creating and accessing dictionaries
2. Dictionary methods and operations
PROGRAM 1
Gowtham is working on a project for a company that manages a fleet of delivery trucks. Each
truck has a unique vehicle number and a corresponding fuel efficiency (in kilometers per
liter). The company needs to analyze the fuel efficiency of its fleet to determine the most
efficient and least efficient vehicles. Your task is to write a Python program that calculates
and prints the maximum and minimum fuel efficiency values from a set of fuel efficiency
data.
The data is provided as a set, and you need to identify the highest and lowest fuel efficiency
values to help the company make data-driven decisions.
Sample Input:
Enter the set of fuel efficiencies: {15, 20, 18, 12, 22}
Sample Output:
25
PROGRAM 2
Jay is working for a software company that provides a system to track inventory in a
warehouse. The warehouse tracks products using a unique product ID for each item.
Occasionally, the system might duplicate product IDs during the entry process due to a bug.
Your task is to write a Python program to help identify the lost product IDs, which are the
items that were entered in the list but have no corresponding entry in the system (i.e.,
duplicates). You can use the set difference method to efficiently find the missing product ID.
Sample Input:
Enter the list of product IDs: 101 102 103 104 102 105 106 103
Sample Output:
Lost product IDs: {'104', '105', '106', '101'}
26
PROGRAM 3
Nithin is working for an online store that tracks the prices of products in a dictionary. The
dictionary contains product names as keys and their corresponding prices as values. Your task
is to write a Python program that allows you to sort the dictionary by either product names
(keys) or prices (values). This will help the store quickly identify the most expensive or
cheapest products, or to list them alphabetically.
Sample Input 1:
Enter the dictionary of products and their prices: {'Laptop': 800, 'Mobile': 400, 'TV': 600,
'Headphones': 100}
Sort by: price
Sample Output 1:
Sorted by price: {'Headphones': 100, 'Mobile': 400, 'TV': 600, 'Laptop': 800}
Sample Input 2:
Enter the dictionary of products and their prices: {'Laptop': 800, 'Mobile': 400, 'TV': 600,
'Headphones': 100}
Sort by: key
Sample Output 2:
Sorted dictionary: {'Headphones': 100, 'Laptop': 800, 'Mobile': 400, 'TV': 600}
27
PROGRAM 4
Kavitha is developing a tool for a text analysis company. One of the features they need is a
program that counts the number of occurrences of each character in a given string. This
information can help analyze the frequency of characters in user-inputted data, such as
passwords or text snippets.
Sample Input:
Enter a string: programming
Sample Output:
Character occurrences: {'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}
28
TECH 507 - FUNCTIONS
THEORY CONCEPTS:
1. Defining Functions, def keyword
2. Parameters and arguments, Return Statement
3. Scope and Lifetime of Variables
4. Lambda Functions
5. Built-in Functions
6. Recursion
PROGRAM 1
Mahirl's Evening Party
Mahirl has started an Event Management Company named “Pineaxe Events and Decors”. To
enhance her event management skills, she organizes an evening party every day during the
first month. The venue details for these parties are as follows:
● Weekday parties are held in “Pineaxe Mahal,” a hall that accommodates up to 1000
people.
● Weekend parties are conducted at “Codissia Open Ground” to accommodate a larger
crowd.
After a month, Mahirl must submit a report to the Board of Directors on the success of these
parties. A party is classified as successful based on the following criteria:
● A weekday party (Monday to Thursday) is considered successful if the number of
attendees is between 700 and 1000, inclusive.
● A weekend party (Friday, Saturday, Sunday) is considered successful if the number of
attendees is at least 1500.
● If the input day is invalid or the number of attendees is negative, the program should
return "Invalid Input".
Write a Python program using a function to classify a party as "Successful", "Unsuccessful",
or "Invalid Input".
29
Input Format
The first line of the input consists of a string that corresponds to the day details. The 7 days
are denoted as “SUN”, “MON”, “TUE”, “WED”, “THU”,“FRI” and “SAT”.Friday, Saturday
and Sunday are considered to be weekends.
The second line of the input consists of an integer that corresponds to the number of people
who have attended the party.
Output Format
Output consists of a string --- “Successful” or “Unsuccessful” or “Invalid Input”.
If the input string is not in one of the valid days or if the input integer is negative, print
Invalid Input.
Refer sample input and output for formatting specifications.
30
PROGRAM 2
Shashwath is exploring a haunted house. The house has multiple rooms arranged in a straight
path. Each room contains a certain number of stairs that lead to the next room. However,
some rooms are blocked, and Shashwath cannot enter them.
Shashwath needs to know the total number of stairs he has to climb to reach the final room in
the house, but there's a catch: the number of stairs in each room varies, and some rooms are
blocked. The challenge is to calculate the total number of stairs using recursion, without
entering the blocked rooms.
Input:
● An array of integers, where each number represents the number of stairs in a room. A
value of 0 means the room is blocked.
● Example: [5, 0, 3, 6, 0, 2]
Output:
● The total number of stairs Shashwath will climb, skipping the blocked rooms.
Sample Input:
[5, 0, 3, 6, 0, 2]
Sample Output:
16
Explanation:
31
ADDITIONAL QUESTIONS:
PROGRAM 3
Ravi has a list of integers. He wants to filter out all numbers that are divisible by either 3 or 5
from the list using a lambda function. Write a Python program that takes a list of integers and
returns a new list containing only those numbers that are divisible by either 3 or 5.
Input Format:
A list of integers (e.g., [10, 15, 23, 33, 50, 7]).
Output Format:
A new list containing numbers divisible by 3 or 5 (e.g., [10, 15, 33, 50]).
Sample Input:
[10, 15, 23, 33, 50, 7]
Sample Output:
[10, 15, 33, 50]
32
TECH 508 - MODULES AND PACKAGES
THEORY CONCEPTS:
1. Importing Modules
2. Standard library modules
3. Creating and using custom modules
4. Packages,Creating packages
5. Importing from packages
PROGRAM 1
Advith is working on a Python project where he needs to perform multiple mathematical
calculations. He frequently uses functions for basic math operations like addition, subtraction,
multiplication, and division. Instead of writing these functions every time, he decides to
import the math module. He also needs to calculate the square root of a number and the sine
of an angle. How would Advith import the math module and use it to calculate the square root
of 16 and the sine of 45 degrees? Write the code snippet.
PROGRAM 2
Ajay is managing a project that involves file handling. He needs to read content from a text
file called data.txt and print the content to the screen. The file is located in the current
working directory. Which Python standard library module should Ajay use to read the file,
and how would he implement it? Write the code to read the file and print its contents.
33
PROGRAM 3
Sumanth has created a Python script called greeting.py that includes a function say_hello() to
greet the user. He wants to use this function in another script called main.py and customize
the greeting based on the time of day. Specifically, the greeting should be:
"Good Morning" if the time is before 12 PM.
"Good Afternoon" if the time is between 12 PM and 5 PM.
"Good Evening" if the time is after 5 PM.
How can Sumanth import and use the say_hello() function from the greeting.py module in the
main.py script and modify the greeting message based on the time of day? Write the code for
both greeting.py and main.py, and include logic to change the greeting based on the time
Sample Input:
Enter your name: Sumanth
Sample Output:
If the current time is before 12 PM:
Good Morning, Sumanth!
34
ADDITIONAL QUESTIONS:
PROGRAM 4
Packages and Creating Packages
Hemanth is developing a package called mathutils to organize his math-related functions.
Inside the mathutils package, he creates two modules: addition.py and subtraction.py, each
containing respective functions to add and subtract numbers.
How should Hemanth create the package, and how can he organize the modules inside it?
Additionally, how would he use the addition and subtraction modules in a script outside the
package?
Sample Output:
Addition Result: 15
Subtraction Result: 5
35
TECH 509 - FILE HANDLING
THEORY CONCEPTS:
1. Introduction to File Handling
2. File Methods: read(), readline(), readlines()
3. write(), writelines()
4. File Modes
PROGRAM 1
Yogi is working on a file management tool for a content organization company. One of his
tasks is to create a feature that reads the content from a source file (provided by the user) and
writes it into a destination file. This feature helps users duplicate files or back up important
information.
Sample Input:
Source file: source.txt (Content: "Hello, this is the source file.")
Destination file: destination.txt
Sample Output:
Content has been successfully copied from source.txt to destination.txt.
36
PROGRAM 2
Mani is working on a text-processing tool for a documentation team. One of the features is to
count the number of lines in a given text file. This will help the team quickly analyze the size
and structure of their documents.
Sample Input:
File: example.txt
Content of example.txt:
Line one.
Line two.
Line three.
Sample Output:
The file example.txt has 3 lines.
37
PROGRAM 3
You are working on a text-editing application for a publishing house. One of your tasks is to
implement a feature that allows users to replace a specific word or phrase in a file with
another. This feature is useful for making bulk edits in documents, such as correcting typos or
updating terminology.
Sample Input:
File: document.txt
Content of document.txt:
Python is a powerful programming language.
Python is used for web development, data analysis, and more.
Word to replace: Python
Replacement word: Java
Sample Output:
Text replacement is complete. The file has been updated.
Java is a powerful programming language.
Java is used for web development, data analysis, and more.
38
TECH 510 - OBJECT-ORIENTED PROGRAMMING (OOP) PART 1
THEORY CONCEPTS:
1. Introduction to Classes and Objects
2. Attributes and Methods
3. Constructors
PROGRAM 1
Construct a class to convert an integer into a roman numeral.
Class name: intToromanConvertor
Method name: int_to_Roman
Hint: Find the below integer and its corresponding roman numeral. (Example: integer 1000 =
roman numeral M, integer 400 =roman CD)
integer= [1000, 900, 500, 400,100, 90, 50, 40,10, 9, 5, 4,1]
roman_equal = ["M", "CM", "D", "CD","C", "XC", "L", "XL","X", "IX", "V", "IV","I"]
Input Format
Input contains integers.
Output Format
Output displays equivalent roman numerals.
Sample Input:
5000
Sample Output
MMMMM
Sample Input:
1253
Sample output:
MCCLIII
39
PROGRAM 2
Guru is developing a new software to automate his business operations, and he needs a
module that can identify pairs of numbers in an array whose sum matches a given target
value. To accomplish this, he wants the solution to be organized using object-oriented
principles, specifically using a class to manage the task.
Input Format
Required Sum in first line.
Number of array elements in the second line.
Array elements in the third line separated by space.
Output Format
Number pair with sum as shown in the sample output.
Sample Input
30
8
14 -15 9 16 25 45 12 8
Sample Output
14 + 16 = 30
-15 + 45 = 30
40
PROGRAM 3
In a business application, the company is developing a time-tracking system. The system
needs to store and display specific date and time details entered by the user. The data includes
the hour, minute, day, month, and year. Additionally, the system needs to calculate the total
number of minutes from a given time and display it.
Guru, the developer, has to write a program that fetches these details, validates the input, and
displays the date, time, and the total number of minutes. If the entered data is invalid (such as
an invalid date or time), the system should return an error message.
Input Format
Single line input with hours, minutes, day, month and year in the same order separated by a
space.
Output Format
Output is displayed as shown in the sample test cases.
Constraints
0<Date<=31; 0<Month<=12: 0<Year<9999; 0<hours<24: 0<minutes<60
Sample Input
7 25 6 9 2018
Sample Output
Date:6-9-2018
Time:7 hrs 25 mins
Total mins:445
Sample Input
28 5 9 3 57
Sample Output
Invalid
41
TECH 511 - OBJECT-ORIENTED PROGRAMMING (OOP) PART 2
THEORY CONCEPTS:
1. Inheritance and its types
PROGRAM 1
REWARD CALCULATION
A new announcement has been made by the Mayor, the Fair will be on for more than a
month. For rewarding customers who actively purchase in the fair, the developers are asked to
compute reward points for credit card purchasing. For a small demo implementation, we now
compute reward points for VISA card and HP VISA card.
Reward Points:
The reward points for a VISA card is 1% of the spending for all kinds of purchases.
For HP Visa card, like VISA card, 1% of the spending for all kinds of purchases and also 10
additional points are given for Fuel purchases.
Create a class named VISACard as Parent class with the following attributes and method.
Attributes: holder_name, card_number
Method Name:
display_details
This method displays the card holder name and card number
compute_reward_points
This method accepts the purchase_type and amount as inputs and displays the reward points
which is 1% of the purchase amount.
42
Input Format
First line of the input consists of the string representing card type (VISA/HPVISA)
Second line of the input consists of the string representing card holder name
Third line of the input consists of the string representing card number
Fourth line of the input consists of the float representing purchase amount
Fifth line of the input consists of the string representing purchase type
Output Format
if the card type is either VISA or HPVISA:
First line of the output consists of card holder name
The second line of the output displays the card number.
Third line of the output displays the reward points
Else display 'Invalid Choice'
Sample Input:
VISA
Mahesh
9871-9874-4569
1500
Groceries
Sample Output:
Mahesh
9871-9874-4569
15.00
Sample Input:
MASTER CARD
Mahesh
9871-9874-4569
1500
Fuel
Sample Output:
Invalid Choice
43
PROGRAM 2
Multilevel Inheritance
We can implement multilevel inheritance in our application. Let's consider the domain 'Stall'
and its types. There exists a multilevel inheritance.
Create a class GoldStall which is the child class of SilverStall with following attributes
Attributes: tv_set (Integer)
Total cost computed by stall cost and TV set cost. Each TV set costs 100Rs.
Create a class PlatinumStall which is the child class of GoldStall (i.e. Multilevel
Inheritance) with following attributes.
Attributes: projector (Integer)
Total cost computed by stall cost, TV set cost and projector cost where each TV set and
projector costs 100 Rs and 500 Rs respectively.
Write a python program to create all the above classes and test the same.
Refer sample input and sample output for better understanding
Input Format
The first line of the input consists of the choice (1 for silver stall, 2 for gold stall and 3 for
platinum stall).
The second line of the input consists of a string representing the name of the stall.
The third line of the input consists of a string representing detail of the stall.
The fourth line of the input consists of a string representing the owner of the stall.
The fifth line of the input consists of oat representing stall cost.
If choice is chosen as 2:
The sixth line of the input consists of an integer representing the number of TV sets.
44
If choice is chosen as 3:
The sixth line of the input consists of an integer representing the number of TV sets.
The seventh line of the input consists of an integer representing the number of projectors.
Output Format
Output displays the total cost depending on the choice.
If the choice is given as other than 1,2 or 3, output displays 'Invalid Choice'
Sample Input:
1
ABC Stall
All home needs available
Kumar
2000
Sample Output:
2000.0
Sample Input:
3
RM Stall
General things
Saravanan
4000
2
1
Sample Output:
5100.0
45
PROGRAM 3
Panvith is organizing a coding challenge for his students to test their understanding of
object-oriented programming concepts. The challenge is based on a fun mathematical puzzle.
He asks his students to create a program where they need to take an integer, break it down
into individual digits, and then compute the sum of all possible pairs of digits (combining the
digits in all possible ways).
Create a parent class DigitOperations that has a method calculate_pairs_sum to perform the
required operation of summing the digit pairs.
Implement a child class SumCalculator that inherits from the parent class DigitOperations
and calls the calculate_pairs_sum method to compute the sum.
For example in case of 1234, the individual digits are 4,3,2,1 and the final sum →
(4+3)+(4+2)+(4+1)+(3+2)+(3+1)+(2+1) = 30.
Input:
● A single integer.
Output:
● The sum of all possible combinations of digit pairs
46
TECH 512 - OBJECT-ORIENTED PROGRAMMING (OOP) PART 3
THEORY CONCEPTS:
1. Polymorphism
2. Abstraction
3. Encapsulation
PROGRAM 1
Function Overloading
Create a function 'add'. The function add should perform the following operation.
1. The first argument should be the datatype of the remaining arguments (str or int) (inp_type)
2. It should be able to get any number of arguments (inp1, inp2, inp3,....)
3. if the data type is 'str', it should perform string concatenation
4. if the data type is 'int', it should perform addition
In the main program, get the user input as below:
inp_type -> type of input
inp1 -> arg1
inp2 -> arg2
inp3 -> arg3
Execute the below statements:
add(inp_type,inp1)
add(inp_type,inp1,inp2)
add(inp_type, inp1,inp2,inp3)
Refer Sample input and output for better understanding
Note: Use the same naming convention as given above.
Input Format
First line of the input consists of data type of the arguments (int or str) representing inp_type
The second line of the input consists of input1 representing inp1.
The third line of the input consists of input2 representing inp2.
The fourth line of the input consists of input3 representing inp3.
Output Format
Output displays the string concatenation or integer addition
47
Refer Sample output.
Sample Input:
int
4
9
15
Sample Output:
4
13
28
Sample Input:
str
Hello
Good
Morning
Sample Output:
Hello
HelloGood
HelloGoodMorning’
48
PROGRAM 2
Write a program to illustrate dynamic polymorphism, create two classes Vehicle and
Motorbike. Motorbike inherits the Vehicle class.
Create a method move() in base class that takes a string as input and print them.
Override the method move() in a derived class that also takes a string as input and prints
them.
Input Format
Input two strings in a separate line
Output Format
Displays the string after execution.
Sample Input
move fast
vehicles
Sample Output
vehicles
move fast
Sample Input
are sweet
mangoes
Sample Output
mangoes
are sweet
49
PROGRAM 3
Calculate Power Consumption of Appliances Using Abstraction
A company is creating a program to monitor the power consumption of household appliances.
To model this, you need to use abstraction in Python.
Create an abstract class Appliance that defines a method power_consumption(hours) to
calculate the power usage based on the hours of usage. Implement the following subclasses
for specific appliances with their respective power usage rates:
● Fan: Consumes 0.075 kWh per hour.
● Refrigerator: Consumes 1.5 kWh per hour.
Write a program that:
Sample Input
Fan
10
Sample Output:
The total power consumption of Fan for 10 hours is 0.75 kWh.
Sample Input:
Refrigerator
24
Sample Output:
The total power consumption of a Refrigerator for 24 hours is 36.0 kWh.
50
ADDITIONAL QUESTIONS:
PROGRAM 4
A bank wants to implement a system to manage customer accounts securely. You need to
write a Python program using encapsulation to protect sensitive data like account balance
and provide controlled access through getter and setter methods.
Create a class BankAccount with the following private attributes:
● account_number: To store the account number.
● balance: To store the account balance.
The class should provide:
● A constructor to initialize the account number and initial balance.
● A method deposit(amount) to add money to the account. Ensure the deposit amount is
positive.
● A method withdraw(amount) to withdraw money. Ensure sufficient balance is
available.
● Getter methods to retrieve the account number and balance.
Demonstrate how encapsulation restricts direct access to private attributes and provides
secure access through defined methods.
Input/Output Format:
Input:
Output:
Sample Input:
12345
51
1000
deposit 500
withdraw 300
withdraw 1500
Sample Output:
Deposit successfully. New balance: 1500.0
Withdrawal successful. New balance: 1200.0
Insufficient funds. Withdrawal failed.
Sample Input:
98765
500
withdraw 600
deposit 200
withdraw 400
Sample Output:
Insufficient funds. Withdrawal failed.
Deposit successful. New balance: 700.0
Withdrawal successful. New balance: 300.0
52
TECH 513 - EXCEPTION HANDLING
THEORY CONCEPTS:
1. Errors and Exceptions Syntax errors vs. runtime errors
2. Try, Except, Finally
3. Raising Exceptions
4. Custom Exceptions
PROGRAM 1
Write a program to limit the user input to only positive integers through the Exception
Handling concept.
If the user gives negative integer value, raise an exception with an error message 'please give
positive integer'.
For a positive integer as an input, display the input.
Input Format
Input consists of an integer.
Output Format
If the user gives a negative integer, Output displays an error message 'please give positive
integer'.
For positive integers as an input, Output displays the input.
53
PROGRAM 2
Get the below customer information for n number of customers separated by spaces.
Name, mobile number, location
Write a program to display only the required customer details.
Refer sample input and output for better understanding.
Input Format
First line of input consists of number of customers (n)
n lines consist of customer details (name,mobile number,Location) separated by commas.
The last line of the input will be an integer which corresponds to customer details in the list
need to be displayed
Output Format
Output displays the customer details if it is present.
Otherwise, display IndexError. (list index out of range)
Sample Input
1
Prabhu,34567890,Coimbatore
1
Sample Output
Prabhu 34567890 Coimbatore
Sample Input
1
Prabhu,34567890,Coimbatore
4
Sample Output
list index out of range
54
PROGRAM 3
Write a function to calculate (a+b)/(a-b) where a and b are positive integers.
Handle error by Exception handling. If a-b is 0, print 'ZeroDivisionError' else print the result.
Input Format
The first line of input contains a positive integer representing a.
The second line of input contains a positive integer representing b.
Output Format
If divide by 0 error occurs, Output displays 'ZeroDivisionError'
Otherwise, Output displays the result.
Sample Input
4
2
Sample Output
3.0
Sample Output
6
6
Sample Output
ZeroDivisionError
55
PROGRAM 4
Mohan, a librarian, is creating software to automate his work. A part of this, he needs to
handle the exception if the purchase quantity is greater than the available quantity.
Create an Exception class called BookQuantityNotAvailableException and use it in the
class called “Book” which is described by its book Id, book title, author, price and quantity
available. Include a method called purchase() taking the purchased quantity as a parameter
and update the quantity available appropriately. Print suitable exception if the purchased
quantity is more than the available quantity. Help Mohan to complete this task. Refer sample
input and output.
Input Format
Book ID
Book Title
Author Name
Price
Quantity available
Quantity purchased
Output Format
New Quantity or Exception
Sample Input:
YCW2019
You can win
Shiv Khera
245
10
5
Sample Output:
New quantity: 5
Sample Input:
YCW2019
56
You can win
Shiv Khera
245
3
5
Sample Output:
InvalidQuantityException: Quantity not available
57
TECH 514 - BASICS OF NumPy
THEORY CONCEPTS:
1. Datatypes, Arrays
In NumPy, datatypes refer to the types of elements that the array can hold. NumPy arrays are
homogeneous, meaning all elements in a given array must be of the same type. NumPy
provides a range of data types that you can specify for the elements of the array.
A NumPy array is a powerful n-dimensional array object, which allows for efficient
mathematical operations, especially for large datasets.
Creating NumPy Arrays:
You can create a NumPy array using the np.array() function by passing a list or another
array-like object.
NumPy also provides functions like np.zeros(), np.ones(), and np.arange() to generate arrays
with specific values.
NumPy provides several functions for performing basic statistical operations on arrays. These
functions are efficient and handle large datasets very well. Here are the most important
statistical functions in NumPy.
58
A. Mean (np.mean)
The mean is the average of all the elements in the array. It is calculated by dividing the sum of
all elements by the number of elements.
Syntax:
np.mean(array)
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
mean_value = np.mean(arr)
print('Mean:', mean_value) # Output: 3.0
B. Median (np.median)
The median is the middle value of the array when the elements are sorted. If the number of
elements is even, the median is the average of the two middle elements.
Syntax:
np.median(array)
Example:
arr = np.array([1, 2, 3, 4, 5])
median_value = np.median(arr)
print('Median:', median_value) # Output: 3.0
59
D. Variance (np.var)
The variance is the square of the standard deviation. It represents the average of the squared
deviations from the mean.
Syntax:
np.var(array)
Example:
arr = np.array([1, 2, 3, 4, 5])
variance_value = np.var(arr)
print('Variance:', variance_value) # Output: 2.0
F. Sum (np.sum)
The sum function returns the sum of all elements in the array.
Syntax:
np.sum(array)
Example:
arr = np.array([1, 2, 3, 4, 5])
sum_value = np.sum(arr)
print('Sum:', sum_value) # Output: 15
60
G. Percentiles (np.percentile)
The percentile function computes the nth percentile of the data. For example, the 50th
percentile is the median.
Syntax:
np.percentile(array, q)
Example:
arr = np.array([1, 2, 3, 4, 5])
percentile_value = np.percentile(arr, 50)
print('50th Percentile:', percentile_value) # Output: 3.0
61
J. Cumulative Product (np.cumprod)
The cumulative product returns the cumulative product of the array elements.
Syntax:
np.cumprod(array)
Example:
arr = np.array([1, 2, 3, 4, 5])
cumulative_prod = np.cumprod(arr)
print('Cumulative Product:', cumulative_prod) # Output: [ 1 2 6 24 120]
PROGRAM 1
Ranganath is tasked with analyzing a dataset that contains integer values. However, for
further analysis, you need to convert the data into floating-point values for precise
calculations. Write a Python program to demonstrate this conversion.
Sample Input:
Enter the list of integers (space-separated):
[10, 20, 30, 40, 50]
Sample Output:
[10. 20. 30. 40. 50.]
62
PROGRAM 2
Kiran needs to create a 2D NumPy array with a specific shape (3, 3) and fill it with random
integers between 1 and 100.
Sample Output:
Generated 2D NumPy Array with Random Integers:
[[50 12 33]
[80 99 44]
[61 22 93]]
63
PROGRAM 3
Jaya Priya is working with a dataset of numerical values representing the test scores of 5
students. The dataset is in the form of a NumPy array. To analyze the data, you need to
compute it to help her with basic statistical measures such as the mean, median, and
standard deviation.
Sample Input:
Test Scores: [85, 90, 78, 92, 88]
Sample Output:
Mean: 86.6
Median: 88.0
Standard Deviation: 4.883
64
PROGRAM 4
Yogi is a data analyst working for a company that tracks the daily number of website visitors.
The marketing team wants to understand the distribution of website traffic over a month. Your
task is to calculate the 25th, 50th, and 75th percentiles of the daily visitors to help the team
understand the spread of website traffic and make better decisions for future campaigns.
Sample Input:
Website Visitors (in thousands): [120, 150, 90, 130, 110, 95, 140, 125, 160, 145, 135, 100,
115, 155, 170, 180, 175, 140, 125, 130, 145, 160, 135, 110, 100, 125, 145, 150, 165, 155]
Sample Output:
25th Percentile: 121.25
50th Percentile (Median): 137.5
75th Percentile: 153.75
Percentiles:
The percentiles are computed using np.percentile(), which takes the dataset and the
desired percentile as input. It helps us understand the distribution of data points:
● 25th Percentile: The value below which 25% of the data points fall.
● 50th Percentile (Median): The middle value of the data when sorted. It divides the
data into two equal halves.
● 75th Percentile: The value below which 75% of the data points fall.
65
ADDITIONAL QUESTIONS
PROGRAM 5
Gagana is working with a dataset that represents the sales of products across two different
regions for three consecutive days. The data is currently stored in a 2x3 NumPy array where
each row represents a region, and each column represents sales for a specific day.
Your task is to reshape this array so that the data is organized such that each column now
represents a region, and each row represents a specific day's sales across the two regions.
Sample Input:
import numpy as np
sales_data = np.array([[200, 250, 300], # Sales for Region 1 on Days 1, 2, and 3
[150, 180, 210]]) # Sales for Region 2 on Days 1, 2, and 3
Sample Output:
Reshaped Sales Data (3, 2):
[[200 150]
[250 180]
[300 210]]
Explanation:
● The original array has the shape (2, 3), where each row corresponds to a region and
each column to a specific day.
● After using .T (transpose), the array is reshaped to (3, 2), where each row now
corresponds to a day and each column to a region's sales for that day.
This reshaping makes the data more readable for analysis by day rather than region.
66
PROGRAM 6
Uma is analyzing the performance of students in a class. The data you have consists of the
scores of 10 students on their final exam. You want to calculate the standard deviation and
variance of their scores to understand the spread of their performance.
Sample Input:
import numpy as np
# Array representing the scores of 10 students
exam_scores = np.array([85, 90, 88, 92, 78, 95, 89, 84, 91, 87])
Sample Output:
Standard Deviation of exam scores: 4.52658811910251
Variance of exam scores: 20.490000000000002
Explanation:
● Standard Deviation (np.std): Measures how spread out the scores are around the
mean. A lower value indicates that the scores are more concentrated around the mean,
while a higher value indicates greater variability.
● Variance (np.var): It is the square of the standard deviation. It represents the average
of the squared differences from the mean.
By calculating these two values, you can better understand how much variation exists in the
exam scores.
67
TECH 515 - BASICS OF PANDAS
THEORY CONCEPTS:
1. Pandas Data Structure & Series
Pandas is a powerful library in Python used for data manipulation and analysis. It provides
two primary data structures: Series and DataFrame.
Here, we'll focus on the Series data structure, its creation, and some important operations.
1. Pandas Data Structure
Series: A one-dimensional labeled array capable of holding any data type (integers, strings,
floats, etc.).
It's like a column in a table, or a dictionary with labels for each element.
2. Pandas Series
A Series is a one-dimensional array-like object that can hold data of any type (integers,
strings, floats, etc.) and is indexed by a set of labels.
68
2. Pandas DataFrame & Loading Data
A DataFrame is the most commonly used data structure in Pandas. It is a two-dimensional,
labeled data structure with columns of potentially different types (e.g., integers, floats, strings,
etc.). It can be thought of as a table or a spreadsheet.
Example
import pandas as pd
df = pd.DataFrame(data)
Output
Name Age Salary
0 John 28 50000
1 Alice 24 55000
2 Bob 30 60000
69
Pandas provides several methods to load data from different file formats into a DataFrame.
Common methods include pd.read_csv(), pd.read_excel(), and pd.read_sql().
3. Descriptive Statistics
1. Central Tendency
2. Dispersion
Interquartile Range (IQR): The range between the 25th and 75th percentiles.
df['column_name'].quantile(0.75) - df['column_name'].quantile(0.25) # IQR
3. Shape of Distribution
70
Maximum: The largest value in the series or column.
df['column_name'].max() # Returns the maximum value
Quantiles: Values that divide the data into equal intervals. The most common quantiles are
25%, 50%, and 75%.
df['column_name'].quantile(0.25) # 25th percentile
df['column_name'].quantile(0.50) # 50th percentile (Median)
df['column_name'].quantile(0.75) # 75th percentile
PROGRAM 1
Neha has a dataset of student scores in various subjects (Math, English, and Science). You
need to analyze the data to find out:
71
PROGRAM 2
Bajarangi is tasked with creating an Employee Data Management System that allows a
company to manage employee information. The system will perform basic operations such as
adding employee data, calculating average salary, sorting employees based on their
performance rating, and saving the updated data to a CSV file.
Features:
1. Add new employee data: Add details such as Employee_ID, Name, Department,
Performance_Rating, and Salary.
2. Calculate average salary for all employees.
3. Sort employees by performance rating (from highest to lowest).
4. Save the updated employee data to a new CSV file.
Sample Input:
Save the file as employee_data.csv in the same folder where your Python script is saved.
Employee_ID,Name,Department,Performance_Rating,Salary
101,John,HR,4.5,50000
102,Alice,IT,3.8,60000
103,Bob,IT,4.2,70000
Sample Output:
72
PROGRAM 3
Imagine Chandana is working as a data analyst for a retail company. You are tasked with
analyzing the sales data for the past year to understand trends and generate key metrics to
guide business decisions. You'll load the sales data, calculate some descriptive statistics, and
generate a summary of the analysis.
CSV File:
Product_ID,Product_Name,Sales_Amount,Date
101,Smartphone,5000,2023-01-15
102,Laptop,7000,2023-01-20
103,Tablet,3000,2023-01-22
104,Headphones,1500,2023-01-25
105,Smartwatch,2500,2023-01-30
106,Laptop,6500,2023-02-05
107,Tablet,3500,2023-02-12
108,Smartphone,6000,2023-02-14
109,Headphones,1800,2023-02-20
110,Smartwatch,2800,2023-03-01
73