0% found this document useful (0 votes)
486 views

Python Skill Course File

This document contains a faculty laboratory manual for the Python Programming skill course at Raghu Engineering College. It provides exercises and questions on various Python topics like software installation, variables, input/output, operators, conditional statements, looping statements, branching statements, lists, tuples, sets, dictionaries, strings, and functions. The exercises are intended to help students learn and practice Python programming concepts through hands-on practice in the laboratory.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
486 views

Python Skill Course File

This document contains a faculty laboratory manual for the Python Programming skill course at Raghu Engineering College. It provides exercises and questions on various Python topics like software installation, variables, input/output, operators, conditional statements, looping statements, branching statements, lists, tuples, sets, dictionaries, strings, and functions. The exercises are intended to help students learn and practice Python programming concepts through hands-on practice in the laboratory.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 73

RAGHU ENGINEERING COLLEGE

ACADEMIC YEAR - 2022-23


II B.Tech- I-Semester(AR20)
FACULTY LABORATORY MANUAL
For

PYTHON PROGRAMMING (Skill Course)


AR20- B.Tech.(Common to CSE & IoT, CS Specializations)

COURSE CODE: 20CS3201

Prepared by
P.S.S. Geethika, Assistant Professor, Department of CSE

1|Page
RAGHU ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB (AR20)
(SKILL COURSE)
Topic Name Exercise Question Question Page
no. No. no.
Software - - Python IDLE installation Procedure 19-
Installation 21

Basics 1 a Correct the below code and execute it: 23


(Variables, val=789
Assignments) print("Given value is: ",VAL)
print("Python is a case sensitive
language")
b Correct the below code, add the code if 24
needed to display the output as given:
Code snippet:
$name='My name"
@age=40
c Write a program to assign single value to 25
multiple variables.
Input-Output 2 a Write a python program to read Regd. No, 26
name from the student and display it on
the screen.
b Display the given float value adjusted to 27
two decimal points
c Write a program to display the below 28
message:
Hello, \nREI\n students
Operators 3 a Write a program that asks the user for a 29
weight in kilograms and converts it to
pounds. There are 2.2 pounds in a
Kilogram
b Write a program that asks the user to enter 30
three numbers (use three separate input
statements). Create variables called total
and average that hold the sum and average
of the three numbers and print out the
values of total and average.
c Write a program to find power of a 31
number without using loops and built-in

2|Page
functions. Base and exponent value to be
taken from the user
Conditional 4 a Write a program to display ‘Valid’ if the 32
Statements value is odd and lesser than 10000,
otherwise ‘Invalid’.
b Write a program that asks the user to enter 33
a length in feet. The program should then
give the user the option to convert from
feet into inches, yards, miles, millimeters,
centimeters, meters, or kilometers. Say if
the user enters a 1, then the program
converts to inches, if they enter a 2, then
the program converts to yards, etc.
c Write a program to check whether given 36
character is alphabet or not, if yes check
whether vowel or consonant.
Looping 5 a Write a program to print the following 37
Statements pattern when n (no. of rows) is given as
input,
If n=4,
*
**
***
****
b Write a program to display first repeating 38
character from the beginning of the given
string. If no repeating is present, display
'None'
c Write a program to print next immediate 39
prime number of the given number
Branching 6 a Write a program to display numbers 40
Statements between 1 to n. But, one of the numbers
between 1 and n is unsafe and that number
shouldn’t be displayed. Assume, unsafe
number is a number which is divisible by
3.
b Write a program to input some numbers 41
repeatedly and print their sum. The
program ends when the users say no more
to enter i.e. normal termination or program
aborts when the number entered is less
than 0
c Write a program which takes a string from 42
the user and display each character in
single line, while iterating skip the printing

3|Page
if the character is ‘t’
Lists 7 a Write a program to compute cumulative 43
product of a list of numbers
b Write a program to find the sum of corner 44
elements in the given matrix
c Write a program that asks the user for an 45
integer and creates a list that consists of
the factors of that integer.
Tuples 8 a Given a list of numbers, write a Python 46
program to create a list of tuples having
first element as the number and second
element as the cube of the number.
b Write a program to extract only extreme K 47
elements, i.e maximum and minimum K
elements in Tuple. Input : test_tup = (3, 7,
1, 18, 9), k = 2 Output : 3, 1, 9, 18
c Write a program to produce a tuple of 48
elements which consists of multiplication
of each element and its adjacent element in
the original tuple.
Sets 9 a Write a program to demonstrate the below 49
functions of Set, i) add() ii) update() iii)
discard()
b Write a program to demonstrate the below 50
functions of Set, i) pop() ii) union() iii)
intersection()
c Write a program to demonstrate the below 51
functions of Set, i) difference ii)
isdisjoint() iii) symmetric_difference()
Dictionaries 10 a Write a program to count the numbers of 52
characters in the string and store them in a
dictionary data structure. Sample Input
hello python Sample Output : 1, e : 1, h :
2, l : 2, n : 1, o : 2, p : 1, t : 1, y : 1
b Write a program to use split and join 53
methods in the string and trace a birthday
with a Dictionary data structure. If
birthday is not found, display a message
‘Not found’. Sample Input 25/08/1991

4|Page
XYZ 12/02/1990 ABC 01/01/1989 PQR
25-08-1991 Sample Output The DOB
25/08/1991 found whose name is XYZ
c Write a program that combines two given 54
lists into a dictionary Sample Input jkl def
abc ghi 10 20 30 40 Sample Output abc:30
def:20 ghi:40 jkl:10
Strings 11 a Write a program to find the reverse of each 56
word in the given list of strings and
display them
b Given a string, the task is to write a 57
program to extract overlapping
consecutive string slices from the original
string according to size K. K and string is
to be given by user
c Given a string, the task is to write a 58
program to replace every Nth character in
a string by the given value K. String, K
and N must be given the user
Functions 12 a Write a function called ‘sum_digits’ that is 59
given an integer num and returns the sum
of the digits of num
b Write a function called ‘first_diff’ that is 60
given two strings and returns the first
location in which the strings differ. If the
strings are identical, it should return -1
c Write a function ‘ball_collide’ that takes 61
two balls as parameters and computes if
they are colliding. Your function should
return a Boolean representing whether or
not the balls are colliding. [functions]
Hint: Represent a ball on a plane as a tuple
of (x, y, r), r being the radius. If (distance
between two balls centers) <= (sum of
their radii) then they are colliding
Modules 13 a Write a program to work with below 62
functions in math module i) cos() ii) ceil()
iii) sqrt

5|Page
b Write a program to work with below 63
functions in os module i) name ii)
getcwd() iii) listdir() – Display only first
10 elements
c Write a program to work with below 64
functions in statistics module i) mean() ii)
median() iii) mode()
Class 14 a Write a python program to illustrate class 65
variable and instance variable for
implementing Robot. In this program the
user needs to implement the robots and
display the number of robots at each time
b Write a class called Time whose only field 67
is a time in seconds. It should have a
method called convert_to_minutes that
returns a string of minutes and seconds
formatted as in the following example: if
seconds is 230, the method should return
'3:50'.
c Write a class called Converter. The user 68
will pass a length and a unit when
declaring an object from the class—for
example, c = Converter(9,'inches'). The
possible units are inches, feet, yards,
miles, kilometers, meters, centimeters, and
millimeters. For each of these units there
should be a method that returns the length
converted into those units. For example,
using the Converter object created above,
the user could call c.feet() and should get
0.75 as the result.
Inheritance 15 a Create a class Person which is having field 70
‘name’, and its sub class Student consists
of a method nameLength() which returns
number of characters in the value assigned
to name field.
b Create a class College which has a 71
getCollegeName function to display
college name and create child class
Department which has setCollegeName,
setDepartment and getDepartment
functions.
c Create a class called ‘Bank’ which consists 73
of a method getroi(), override getroi()
method in its sub classes SBI, ICICI

6|Page
classes to return different rate of interest
values.
Exception 16 a Write a program to perform addition of 74
Handling two numbers in a try block and wrote
except block to handle ValueError if
invalid data is given for input () function
b Write a program to find the average of list 75
of numbers given and write exception
handling code with single except block to
handle ZeroDivisionError and ValueError
c Write a program to display an element of a
list given by asking an index value from 76
the user and also write except block to
handle IndexError.

7|Page
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vision of the Department

To generate competent professionals to become part of the industry and


research organizations at the national and international levels

Mission of the Department

To impart high quality professional training in undergraduate level with


emphasis on basic principles of Computer Science and Engineering and
to foster leading edge research in the fast-changing field
To inculcate professional behavior, strong ethical values, innovative
research capabilities and leadership abilities in the young minds so as to
work with a commitment

8|Page
LIST OF PROGRAM OUTCOMES

1) Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2) Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

3) Design/development of solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

4) Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.

5) Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.

6) The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.

7) Environment and sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

8) Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.

9) Individual and team work: Function effectively as an individual, and as a member or


leader in-diverse teams, and in multidisciplinary settings.

10) Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.

11) Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member

9|Page
and leader in a team, to manage projects and in multidisciplinary
environments.

12) Life-long learning: Recognize the need for, and have the preparation and ability to
engage independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES

PSO DESCRIPTION
PS01 Foundation of mathematical concepts: To use mathematical methodologies to
crack problem using suitable mathematical analysis, data structure and suitable
algorithm.
PSO2 Foundation of Software development: the ability to grasp the software
development lifecycle and methodologies of software systems. Possess competent
skills and knowledge of software design process. Familiarity and practical
proficiency with a broad area of programming concepts and provide new ideas and
innovations towards research
PSO3 Foundation of Network development: To include knowledge required for
configuration of computer networks and connections of related networking
components. Along with that inculcate how to implement wireless Internet
connections and how to protect networks from Cyber attacks

Program Educational Objectives (PEOs)

PEO No. Program Educational Objectives Statements


PEO1 To produce graduates who have strong foundation in mathematics, science,
engineering fundamentals, laboratory and work-based experiences to formulate and
solve engineering problems in computer science engineering domains and shall have
proficiency in implementation software tools and languages
PEO2 To progressively impart training to the students for success in various engineering
positions within the core areas in computer science engineering, computational or
adapting themselves to latest trends by learning themselves
PEO3 To produce graduates having the ability to pursue advanced higher studies and
research. To have professional and communication skills to function as leaders and
members of multi-disciplinary teams in engineering and other industries with strong
work ethics, organizational skills, team work and understand the importance of being a
thorough professional

10 | P a g e
COURSE OBECTIVES
The aim of this course is,
 To learn about Python programming language syntax, semantics, basics and
the runtime environment
 To be familiarized with general computer programming concepts like
conditional execution, loops & functions
 To be familiarized with data structures, object-oriented programming and
exception handling in Python

Course Outcomes:
By the end of this course, the student is able to
 Write, Test and Debug Python Programs
 Solve coding tasks related conditional execution, loops
 Use functions and represent Compound data using Lists, Tuples and
Dictionaries etc. And to use different concepts of object oriented
programming.

CO-PO Co-relation matrix:


PO-1 PO- PO-3 PO-4 PO-5 PO-6 PO-7 PO-8 PO- PO-10 PO- PO-12
2 9 11
CO- 1 2 2 3 1 - - - - - - 1
1
CO- 1 2 2 3 1 - - - - - - 1
2
CO- 1 2 2 3 1 - - - - - - 1
3

COURSE OBECTIVES
The aim of this course is,
 To learn about Python programming language syntax, semantics, basics and
the runtime environment
 To be familiarized with general computer programming concepts like
conditional execution, loops & functions
 To be familiarized with data structures, object-oriented programming and
exception handling in Python

11 | P a g e
Course Outcomes:
By the end of this course, the student is able to
 Write, Test and Debug Python Programs
 Solve coding tasks related conditional execution, loops
 Use functions and represent Compound data using Lists, Tuples and
Dictionaries etc. And to use different concepts of object oriented
programming.

12 | P a g e
PYTHON PROGRAMMING (Skill Course)
AR20- B.Tech.(Common to CSE & IoT, CS Specializations)
II-B.Tech., I-Semester
L T P C
1 0 2 2
Course Code: 20CS3201 Internal Marks: 15
External Marks: 35
Course Objectives:
The aim of this course is,
 To learn about Python programming language syntax, semantics, basics and the runtime
environment
 To be familiarized with general computer programming concepts like conditional
execution, loops & functions
 To be familiarized with data structures, object-oriented programming and exception
handling in Python
Course Outcomes:
By the end of this course, the student is able to
 Write, Test and Debug Python Programs
 Solve coding tasks related conditional execution, loops
 Use functions and represent Compound data using Lists, Tuples and Dictionaries etc.
And to use different concepts of object oriented programming.

Exercise 1- Basics (Variables, Assignment)


1. Correct the below code and execute it:
val=789
print(“Given value is: “,VAL)
print(“Python is a case sensitive language”) [Variables]
2. Correct the below code, add the code if needed to display the output as given:
Code snippet:
$name=’My name”
@age=40
Desired output:
Name: My name
Age: 40 [Variables]
3. Write a program to assign same value to multiple variables in a single line of statement.

[Variables]
Exercise 2- Input Output
1. Write a program to read Regd. No, name from the student and display it on the screen.

[input() function]
2. Write a program to display the value of PI (3.1416) adjusted to two decimal points.

[input() function]

13 | P a g e
3. Write a program to display the below message: Hello, \nREI\n studennts
[Escape Character]
Exercise 3- Operators
1. Write a program that asks the user for a weight in kilograms and converts it to pounds.
There are 2.2 pounds in a kilogram [Arithmetic Operator]
2. Write a program that asks the user to enter three numbers (use three separate input
statements). Create variables called total and average that hold the sum and average of
the three numbers and print out the values of total and average[Arithmetic Operator]
3. Write a program to find power of a number without using loops and built-in functions.
Base and exponent value to be taken from the user [Arithmetic Operator]
Exercise 4- Conditional Statements
1. Write a program to display ‘Valid’ if the value is odd and lesser than 10000, otherwise
‘Invalid’. [if-else]
2. Write a program that asks the user to enter a length in feet. The program should then give
the user the option to convert from feet into inches, yards, miles, millimeters, centimeters,
meters, or kilometers. Say if the user enters a 1, then the program converts to inches, if
they enter a 2, then the program converts to yards, etc. [elif]
3. Write a program to check whether given character is alphabet or not, if yes check whether
vowel or consonant. [nested-if]
Exercise 5- Looping Statements
1. Write a program to print the following pattern when n (no. of rows) is given as input, If
n=4,
*
**
***
**** [loops]
2. Write a program to display first repeating character from the beginning of the given
string. [loops]
3. Write a program to print next immediate prime number of the given number. [loops]
Exercise 6- Branching Statements
1. Write a program to display numbers between 1 to n. But, one of the numbers between 1
and n is unsafe and that number shouldn’t be displayed. Assume, unsafe number is a
number which is divisible by 3. [continue]
2. Write a program to input some numbers repeatedly and print their sum. The program
ends when the users say no more to enter i.e. normal termination or program aborts when
the number entered is less than 0. [break]
3. Write a program which takes a string from the user and display each character in single
line, while iterating skip the printing if the character is ‘t’. [continue]
Exercise 7- Lists
1. Write a program to compute cumulative product of a list of numbers [list]
2. Write a program to find the sum of corner elements in the given matrix [list]
3. Write a program that asks the user for an integer and creates a list that consists of the
factors of that integer. [list]
Exercise 8- Tuples
1. Given a list of numbers, write a Python program to create a list of tuples having first
element as the number and second element as the cube of the number. [tuple]

14 | P a g e
2. Write a program to extract only extreme K elements, i.e maximum and
minimum K elements in Tuple.
Input : test_tup = (3, 7, 1, 18, 9), k = 2
Output : 3, 1, 9, 18 [tuple]
3. Write a program to produce a tuple of elements which consists of multiplication of each
element and its adjacent element in the original tuple. [tuple]

Exercise 9- Sets
1. Write a program to demonstrate the below functions of Set,
i) add() ii) update() iii) discard() [set]
2. Write a program to demonstrate the below functions of Set,
i) pop() ii) union() iii) intersection() [set]
3. Write a program to demonstrate the below functions of Set,
i) difference ii) isdisjoint() iii) symmetric_difference() [set]
Exercise 10- Dictionaries
1. Write a program to count the numbers of characters in the string and store them in a
dictionary data structure.
Sample Input
hello python
Sample Output
: 1, e : 1, h : 2, l : 2, n : 1, o : 2, p : 1, t : 1, y : 1 [dictionary]
2. Write a program to use split and join methods in the string and trace a birthday with a
Dictionary data structure. If birthday is not found, display a message ‘Not found’.
Sample Input
25/08/1991 XYZ 12/02/1990 ABC 01/01/1989 PQR
25-08-1991
Sample Output
The DOB 25/08/1991 found whose name is XYZ [dictionary]
3. Write a program that combines two given lists into a dictionary
Sample Input
jkl def abc ghi
10 20 30 40
Sample Output
abc:30
def:20
ghi:40
jkl:10 [dictionary]
Exercise 11- Strings
1. Write a program to find the reverse of each word in the given list of strings and display
them. [strings]
2. Given a string, the task is to write a program to extract overlapping consecutive string
slices from the original string according to size K. K and string is to be given by user.

[strings]
3. Given a string, the task is to write a program to replace every Nth character in a string by
the given value K. String, K and N must be given the user. [strings]

15 | P a g e
Exercise 12- Functions
1. Write a function called ‘sum_digits’ that is given an integer num and returns the sum of
the digits of num. [functions]
2. Write a function called ‘first_diff’ that is given two strings and returns the first location
in which the strings differ. If the strings are identical, it should return -1. [functions]
3. Write a function ‘ball_collide’ that takes two balls as parameters and computes if they are
colliding. Your function should return a Boolean representing whether or not the balls are
colliding. [functions]
Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius. If (distance
between two balls centers) <= (sum of their radii) then (they are colliding)
Exercise 13- Modules
1. Write a program to work with below functions in math module
i) cos() ii) ceil() iii) sqrt
2. Write a program to work with below functions in os module
i) name ii) getcwd() iii) listdir() – Display only first 10 elements
3. Write a program to work with below functions in statistics module
i) mean() ii) median() iii) mode()
Exercise 14- Class
1. Write a python program to illustrate class variable and instance variable for implementing
Robot. In this program the user need to implement the robots and display the number of
robots at each time. [class & instance variables]
2. Write a class called Time whose only field is a time in seconds. It should have a method
called convert_to_minutes that returns a string of minutes and seconds formatted as in the
following example: if seconds is 230, the method should return '5:50'.[instance methods]
3. Write a class called Converter. The user will pass a length and a unit when declaring an
object from the class—for example, c = Converter(9,'inches'). The possible units are
inches, feet, yards, miles, kilometers, meters, centimeters, and millimeters. For each of
these units there should be a method that returns the length converted into those units. For
example, using the Converter object created above, the user could call c.feet() and should
get 0.75 as the result. [parameterized constructor]
Exercise 15- Inheritance
1. Create a class Person which is having field ‘name’, and its sub class Student consists of a
method nameLength() which returns number of characters in the value assigned to name
field. [simple inheritance]
2. Create a class College which has a getCollegeName function to display college name and
create child class Department which has setCollegeName, setDepartment and
getDepartment functions. [simple inheritance]
3. Create a class called ‘Bank’ which consists of a method getroi(), override getroi() method
in it’s sub classes SBI, ICICI classes to return different rate of interest values.
[method overriding]
Exercise 16- Exception Handling
1. Write a program to perform addition of two numbers in a try block and wrote except
block to handle ValueError if invalid data is given for input() function.[ValueError]
2. Write a program to find the average of list of numbers given and write exception
handling code with single except block to handle ZeroDivisionError and ValueError

16 | P a g e
[except: block]
3. Write a program to display an element of a list given by asking an index value from the
user and also write except block to handle IndexError. [IndexError]

RAGHU ENGINEERING COLLEGE


(Autonomous)
(Affiliated to JNTU-KAKINADA)
Visakhapatnam-531162

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

Name of the Laboratory : Python Programming (Developed/Updated)

Subject Code : 20CS3201


Academic Year : 2022-23
Regulation : AR20
Department : CSE
Program : B.TECH
Year : 2ND
Semester : 1ST

IQAC Committee

Signature(s): Signature(s):

17 | P a g e
Name(s): Name(s):

Faculty signature HoD, CSE

LAB INFORMATION SHEET (SCHEME OF EVALUATION)


PYTHON PROGRAMMING (Skill Course)
AR20- B.Tech.(Common to CSE & IoT, CS Specializations)
II-B.Tech., I-Semester

The Evaluation consists of Internal and External Evaluation


 Internal Evaluation: 15 Marks
 External Evaluation: 35 Marks

LAB EVALUATION
Internal Daily Evaluation 10 Marks 15 Marks
Exam 5 Marks
External End Exam 25 Marks 35 Marks
Viva 10 Marks
Total 50 Marks

18 | P a g e
IDLE INSTALLATION PROCESS
SOFTWARE INSTALLATION PROCESS
Installing on Windows

 Open website https://www.python.org/  from your web browser.

 Click at Downloads. Different options will be shown. You can


choose the version you want to download as per your operating
system.
 We can click at all releases if we want to download an older version
of Python.
 Double click at Python installer donwloaded on your computer.
Dialog box will appear as follow:

 Click at Run button to continue installation. Dialog Box will


appear as

19 | P a g e
 Click at Install Now.
 Pthon installation will start and following window will appear

 When installation gets completed following window will appear

 Click close to close this window.

20 | P a g e
Exercise 1 # a
Question:
Correct the below code and execute it:
val=789
print("Given value is: ",VAL)
print("Python is a case sensitive language")
Objective:
To learn the concepts of Variables usage with print
Requirement Analysis:
 Spyder IDE installation
 Write the code
 Verify the error
 Execute the code
Program:
val=789
print("Given value is: ",val)
print("Python is a case sensitive language")

Output:

21 | P a g e
Exercise 1 #b

Question
Correct the below code, add the code if needed to display the output as given:
Code snippet:
$name='My name"
@age=40

Objective
To learn variable naming conventions

Requirement Analysis :
 Spyder IDE installation
 Write the corrected code
 Execute the code

Program
name="My name"
age=40
print("Name:",name)
print("Age:",age)

output:

22 | P a g e
Exercise 1 #c
Question
Write a program to assign single value to multiple variables.
Objective
To implement variable assignment
Requirement Analysis :
 Input two variables
 Assign the values while reading the input
 The datatype can be any type
 Print them using separate print statement

Program
x=y=int(input("Enter a value"))
print("x=",x)
print("y=",y)

Output:

23 | P a g e
Exercise 2 #a
Question
Write a python program to read Regd. No, name from the student and display it on the screen
Objective :
To learn input and output functionality in python
Requirement Analysis :
 Declare a variable for Regd No and read using input statement
 Declare a variable student name and read using input statement
 Print each value separately using print statement

Program
Regd_no=input("Enter Student Roll Number :")
Student_name=input("Enter Student Name : ")
print("Regd. No:" + Regd_no+ "")
print("Name:" + Student_name +"")

Output:

24 | P a g e
Exercise 2 #b
Question

Display the given float value adjusted to two decimal points


Objective :
Learn float type usage and its decimal positions
Requirement Analysis :
 Declare a variable for float value and read using input
 Print the value using round built in function

Program
float_value=float(input("Enter a float value : "))
print("Value rounded to 2 Decimals : ",round(float_value,2))

Output

25 | P a g e
Exercise 2 #c
Question
Write a program to display the below message:
Hello, \nREI\n students
Objective :
To learn escape sequence
Requirement Analysis :
Use escape sequence \n appropriately using print statement

Program
print("Hello, \\nREI\\n students")
Output:

26 | P a g e
Exercise 3 #a
Question
Write a program that asks the user for a weight in kilograms and converts it to pounds. There are
2.2 pounds in a Kilogram
Objective
To learn usage of arithmetic operators
To implement round built in function to solve the given problem using conversion

Requirement Analysis:
 Read a variable kg using input function
 Convert into pounds using the given formula
 Assign the value to pounds
 Print the output

Program
kg=float(input("Enter Weight in Kilograms "))
pounds = kg * 2.2
print(kg,"kilograms = ",round(pounds , 3), "pounds ")

Output:

27 | P a g e
Exercise 3 #b
Question

Write a program that asks the user to enter three numbers (use three separate input statements).
Create variables called total and average that hold the sum and average of the three numbers and
print out the values of total and average
Objective
To implement input statements
To understand variable concept
To apply arithmetic operators

Requirement Analysis:
 Read first number using input function
 Read second number using input function
 Read third number using input function
 Compute sum for the above variables
 Compute average for the sum
 Print the sum and average

Program
first_number=int(input("Enter First Number : "))
second_number=int(input("Enter Second Number : "))
third_number=int(input("Enter Third Number : "))
sum_numbers=first_number+second_number+third_number
print("Sum of three numbers is : ",sum_numbers)
print("Average value is : ",round((sum_numbers/3),2))

Output:

28 | P a g e
Exercise 3 #c
Question
Write a program to find power of a number without using loops and built-in functions. Base and
exponent value to be taken from the user
Objective
To learn usage of operators
Requirement Analysis :
 Read two variable x and y
 Use the exponent operator x upon y

Program
print("Finding x power y ")
print("----------------------")
x=int(input("Enter x value : "))
y=int(input("Enter y value : "))
print(x,"to the power of",y,"is",x**y)

Output:

29 | P a g e
Exercise 4# a
Question
Write a program to display ‘Valid’ if the value is odd and lesser than 10000, otherwise ‘Invalid’.
Objective :
To learn and implement decision making using if condition

Requirement Analysis :
 Reading a value using input
 Verify if its odd and compare if it is less than 10000
 Print the message as per the condition

Program
value=int(input("Enter a value : "))
if(value%2==1 and value<10000):
print("Valid")
else:
print("Invalid")

Output:

30 | P a g e
Exercise 4# b
Question
Write a program that asks the user to enter a length in feet. The program should then give the
user the option to convert from feet into inches, yards, miles, millimeters, centimeters, meters, or
kilometers. Say if the user enters a 1, then the program converts to inches, if they enter a 2, then
the program converts to yards, etc.
Use below conversion formulas:
1. inches=multiply the length value with 12
2. yards=divide the length value by 3
3. miles=divide the length value by 5280
4. millimeters=for an approximate result, multiply the length value by 305
5. centimeters=multiply the length value with 30.48
6. meters=for an approximate result, divide the length value by 3.281
7. kilometers=for an approximate result, divide the length value by 3281

Objective
To learn and implement operators in C++
Requirement Analysis :
Read the length using input
Use the given formulas to calculate the result
Display the result in appropriate format

Program
print("Converter ")
print("-----------------------")
print("List of options ")

31 | P a g e
print("------------------------")
print("1. To Inches")
print("2. To Yards")
print("3. To miles")
print("4. To Millimeters")
print("5. To Centimeters")
print("6. To Meters")
print("7. To Kilometers")
print("------------------------")
print()
option=int(input("Enter your option :"))
length=float(input("Enter length in feet : "))

if(option==1):
result=length*12
print("Given length in inches is %.4f"%(result))
elif(option==2):
result=length/3
print("Given length in yards is %.4f"%result)
elif(option==3):
result=length/5280
print("Given length in miles is %.4f"%result)
elif(option==4):
result=length*305
print("Given length in millimeters is %.4f"%result)
elif(option==5):
result=length*30.48
print("Given length in centimeters is %.4f"%result)
elif(option==6):
result=length/3.281
print("Given length in meters is %.4f"%result)
else:
result=length/3281
print("Given length in kilometers is %.4f"%result)

Output:

32 | P a g e
Exercise 4# c
Question
Write a program to check whether given character is alphabet or not, if yes check whether vowel
or consonant
Objective
To learn and implement operators
Requirement Analysis :
 Read the character
 Compare the input with appropriate values
 Display the result

Program
alpha=input("Enter a character : ")
if((alpha>='A' and alpha<='Z') or (alpha>='a' and alpha<='z')):
if(alpha=='a' or alpha=='A' or alpha=='e' or alpha=='E' or alpha=='i' or alpha=='I' or alpha=='o'
or alpha=='O' or alpha=='u' or alpha=='U'):

33 | P a g e
print("vowel")
else:
print("consonant")
else:
print("Not an alphabet")

Output

Exercise 5# a
Question
Write a program to print the following pattern when n (no. of rows) is given as input,
If n=4,
*
**
***
****

Objective :
 To learn usage of loops
 Apply the problem solving technique using loops concepts
Requirement Analysis:
 Take input no of rows the user need to print
 Assign the symbol “*” to a variable
 Print using for loop with range function
Program

34 | P a g e
rows=int(input("Enter number of rows "))
star="*"
for i in range(1,rows+1):
print(star*i)

Output:

Exercise 5# b
Question
Write a program to display first repeating character from the beginning of the given string. If no
repeating is present, display 'None'
Objective:
To implement string concepts along with decision making
Requirement Analysis:
 Read a string value
 Set count  0
 Compare every string characters using for loop
 Print the string character when both the index values are equal and set count  1
 If count value is 1 then break the loop
 If count value is 0 print a message “None”

Program
string=input("Enter a string")
count=0

35 | P a g e
for i in range(0,len(string)):
for j in range(i+1,len(string)):
if(string[i]==string[j]):
print(string[i])
count=1
if(count==1):
break
if(count==0):
print("None")

Output:

Exercise 5# c
Question
Write a program to print next immediate prime number of the given number
Objective:
To Learn looping concept and apply prime number logic to print next prime value
Requirement Analysis :
 Read a number
 Set count0
 Check if the number is divisible by the values ranging from 1 to the number
 If divisible increase count value
 If count is 2 print the value along with the message

Program
number=int(input("Enter any number :"))
count=0
val=number+1
while(1):
count=0

36 | P a g e
for i in range(1,val+1):
if(val%i==0):
count=count+1
if(count==2):
print("The next immediate prime numbers is",val)
break
else:
val=val+1

Output:

Exercise 6# a
Question
Write a program to display numbers between 1 to n. But, one of the numbers between 1 and n is
unsafe and that number shouldn’t be displayed. Assume, unsafe number is a number which is
divisible by 3
Objective :
To learn loop concepts and decision making
Requirement Analysis :
 Read a number
 And check if the number is visible by 3 ranging from 1 to the number+1
 If the remainder is 0 continue the loop
 Else print the value

Program
number=int(input("Enter a number : "))
for val in range(1,number+1):
if(val%3==0):

37 | P a g e
continue
else:
print(val,end=" ")

Output:

Exercise 6# b
Question
Write a program to input some numbers repeatedly and print their sum. The program ends when
the users say no more to enter i.e. normal termination or program aborts when the number
entered is less than 0
Objective:
To learn the concepts of loops and decision making
Requirement Analysis :
 Print a message to the user stating to accept the input and to quit a negative number is
the input
 Read the input continuously using infinite loop
 If the number is negative then break the loop
 Else add the value to sum
 Finally print the sum
Program
print("Enter the numbers , to quit give a negative number :")
sum_val=0

38 | P a g e
while(1):
i=int(input())
if(i<0):
break;
else:
sum_val+=i
print("Sum of the values is ",sum_val)

Output:

Exercise 6# c
Question
Write a program which takes a string from the user and display each character in single line,
while iterating skip the printing if the character is ‘t’

Objective:
To learn the decision making and loops concepts
Requirement Analysis :
 Read a string
 For every character in the string
 Compare if it is’t’ or ‘T’
 If condition is satisfied then continue the loop else print the character
Program
string=input("Enter any string : ")
for char in string:
if (char=='t' or char=='T'):
continue

39 | P a g e
else:
print(char)
output :

Exercise 7# a
Question :
Write a program to compute cumulative product of a list of numbers
Objective :
To learn lists concepts , decision making , loops

Requirement Analysis:
 Read a string
 Declare empty list
 For every value in the string
 Compare if the string is not empty , then add it to the list
 To find the product set a variable j1
 Iterating through the loop multiply every value of list with j and append it to the newlist

Program
string=input("Enter list of numbers with a separator space : ")

40 | P a g e
mlist=[]
for i in string:
if i!=" ":
mlist.append(int(i))
new_list=[]
j=1
for i in range(0,len(mlist)):
j*=mlist[i]
new_list.append(j)

print(new_list)
Output:

Exercise 7#b
Question
Write a program to find the sum of corner elements in the given matrix
Objective :
To learn matrix concepts
Requirement Analysis:
 Declare an empty matrix
 Read the size
 Read the input .
 Since the input is in the form a string (every row)
 Split it and convert every value to an int and add it to the list
 For corner elements sum iterate for rows and columns values
 Compare if the of row index and column index is 0 or n-1 if equal then add it to sum

Program
mat=[]
n=int(input("Enter size"))

41 | P a g e
for x in range(n):
str1=input()
list1=str1.split()
nl=[int(x) for x in list1]
mat.append(nl)
sum1=0
for x in range(len(nl)):
for y in range(len(nl)):
if((x==0 or x==n-1) and (y==0 or y==n-1)):
sum1+=mat[x][y]
print("Sum of corner elements ",sum1)

Output:

Exercise 7# c
Question
Write a program that asks the user for an integer and creates a list that consists of the factors of
that integer.
Objective :
to implement list concepts and loops
Requirement Analysis:
 read a value
 iterate using for loop diving the number from 1 to the number
 if the remainder is 0 then append the value to list

Program
val=int(input("Enter a number :"))
newlist=[x for x in range(1,val+1) if(val%x==0)]
print("Factors of newlist",newlist)

42 | P a g e
Output:

Exercise 8 # a
Question
1. Given a list of numbers, write a Python program to create a list of tuples having first element
as the number and second element as the cube of the number
Objective :
To learn list ,split function
Requirement Analysis :
 Read the values
 Use split function to split the values as the input is a string format
 Convert every value to integer using comprehensive list syntax
 Now make a tuple with a pair of value and its cube add it to an empty list using
comprehensive list

Program
string=input("Enter the values : ")
numlist=string.split()
newlist = [int(x) for x in numlist]

43 | P a g e
result=[(val,(val**3)) for val in newlist]
print(result)

Output:

Exercise 8 # b
Question:
Write a program to extract only extreme K elements, i.e maximum and minimum K elements in
Tuple. Input : test_tup = (3, 7, 1, 18, 9), k = 2 Output : 3, 1, 9, 18
Objective:
To solve the problem using list , tuple and function split()
Requirement Analysis:
 Read the values
 Take the input k from user
 Split the values and store them in a list
 Convert each value to integer using comprehensive list
 Sort the values using sort function
 Create an empty list
 Append the values in the new list
 From the length-k to length add the values in new list
 Print the result as a tuple

44 | P a g e
Program
str1=input("Enter values ")
k=int(input("Enter the k value to extract : "))
list1=str1.split(',')
nl=[int(x) for x in list1]
nl.sort()
resl=[]
for i in range(k-1,-1,-1):
resl.append(nl[i])
for i in range((len(nl)-k),len(nl)):
resl.append(nl[i])
print(tuple(resl))

Output:

Exercise 8 # c
Question
Write a program to produce a tuple of elements which consists of multiplication of each element
and its adjacent element in the original tuple.
Objective :
To learn tuple concepts
Requirement Analysis :
 Read the values
 Convert the values to list using split function
 Create an empty list

Program
string=input("Enter the values : ")
mlist=string.split(',')
nl=[int(x) for x in mlist]
res_list=[]

45 | P a g e
for i in range(0,len(nl)-1,2):
k=nl[i]*nl[i+1]
res_list.append(k)

minval=res_list[0]
for i in res_list:
if(minval>i):
minval=i
if(len(nl)%2==1):
res_list.append(nl[len(nl)-1]*min)
print(tuple(res_list))

Output:

Exercise 9# a
Question:
Write a program to demonstrate the below functions of Set, i) add() ii) update() iii) discard()
Objective:
To learn the set concepts and set operations
Requirement Analysis:
 Create a set with some values
 Read any number from user to add to first set
 Read any number from user to remove an item from second set
 Update the sets
 Sort them in reverse order
 Apply discard function to remove the value
 Display the values of final sets

Program
set1={3,2,4,9}

46 | P a g e
print(set1)
n=int(input("Enter a number to add in the set "))
set2={10,8,11}
print(set2)
i=int(input("Enter the element to remove from the set "))
l1=[]
set1.add(n)
print("First set of values Sorted : ",sorted((list(set1))))
set1.update(set2)
print("Updated values Sorted in Reverse order : ",sorted(list(set1),reverse=True))
set1.discard(i)
print("Now the values is :",sorted(list(set1)))

Output:

Exercise 9 # b
Question
Write a program to demonstrate the below functions of Set, i) pop() ii) union() iii) intersection()
Objective:
To learn set operations
Requirement Analysis :
 Create three sets with values
 Show the popped element from the set
 Create an empty set
 Apply union operation on both the sets and assign it to new set
 Display the values
 Apply intersect operation and display them
Program
set1={"C"}
set2={"Python","Java",47,"C++"}

47 | P a g e
set3={"JS",57,"SQL",47,"Python"}
print("Popped element is : ")
print(set1.pop())
set2,set3={str(x) for x in set2},{str(y) for y in set3}
set4={}
set4=set2.union(set3)
print("Values of combined set are :")
print(sorted(list(set4)))
print("Values that are common : ")
print(sorted(list(set2.intersection(set3))))

Output:

Exercise 9 # c
Question
Write a program to demonstrate the below functions of Set, i) difference ii) isdisjoint() iii)
symmetric_difference()
Objective :
To learn set operations
Requirement Analysis:
 Create a set
 Convert each value to string and store them in the sets
 Apply set difference operation
 Check if the sets are disjoint and display the result
 Apply symmetric difference operation and display the result
Program
set1={"Python","Java",47,"C++"}
print("Enter values to create a set with comma seperator :")
set2=str(input())

48 | P a g e
l1=set2.split(',')
set2=set(l1)
set2,set1={str(x) for x in set2},{str(y) for y in set1}
print("set1 - set2 values in sorted order : ")
print(sorted(list(set1.difference(set2)),reverse=True))
print("Disjoint sets : ",end="")
print('True') if set1.isdisjoint(set2) else print('False')
print("Symmetric difference values :")
print(sorted(list(set1.symmetric_difference(set2))))

Output:

Exercise 10 #a
Question
Write a program to count the numbers of characters in the string and store them in a dictionary
data structure. Sample Input hello python Sample Output : 1, e : 1, h : 2, l : 2, n : 1, o : 2, p : 1, t :
1, y : 1
Objective:
To learn dictionaries
Requirement Analysis :
 Read a string
 Create an empty dictionary
 Store the count of each string in the dictionary using key value pair
 Display items of dictionary using dictionary function

Program
str1=input("Enter a string to count characters :")

49 | P a g e
str1=sorted(str1)
d={}
for x in str1:
d[x]=str1.count(x)
for u,v in d.items():
print(u,':',v)

Output:

Exercise 10 # b
Question
Write a program to use split and join methods in the string and trace a birthday with a Dictionary
data structure. If birthday is not found, display a message ‘Not found’. Sample Input 25/08/1991
XYZ 12/02/1990 ABC 01/01/1989 PQR 25-08-1991 Sample Output The DOB 25/08/1991 found
whose name is XYZ
Objective:
To learn dictionaries
Requirement Analysis:
 Read a string
 Split it and assign to a variable as list values
 Create an empty dictionary
 Assign the values of first list value as key and second list value as value in the dictionary
 Replace the ‘-‘ character with ‘/’
 For every key value pair in the dictionary compare the user input
 If matching then display else show the message “DoB not found”

50 | P a g e
Program
str1=input("Enter DOB and strings :")
l1=str1.split(' ')
d=dict()
flag=0
for i in range(0,len(l1)-1,2):
d[l1[i]]=l1[i+1]
s=input("Enter the DOB to find : ")
s=s.replace('-','/')
for x,y in d.items():
if(x==s):
print('The DOB',x,'found whose name is',y)
flag=1
break
if(flag==0):
print("DOB is not found!!")
Output:

Exercise 10 # c
Question:
Write a program that combines two given lists into a dictionary Sample Input jkl def abc ghi 10
20 30 40 Sample Output abc:30 def:20 ghi:40 jkl:10
Objective :
To learn dictionary concepts
Requirement Analysis:
 Read the keys from user
 Read the values from user
 Separate keys and values into two different lists using split() function
 Combine them using zip function with dict cast operation and store them in a separate
dictionary
 Print the values using key value pair with a for loop

51 | P a g e
Program
s1=input("Enter values for key : ")
s2=input("Enter values for values :")

l1=s1.split(' ')
l2=s2.split(' ')
dict1=dict(zip(l1,l2))
l=list(dict1.items())
l.sort()
print("Dictionary : ")
dict1=dict(l)
for x,y in dict1.items():
print(x+':'+y)

Output:

Exercise 11 # a
Question
Write a program to find the reverse of each word in the given list of strings and display them
Objective:
To learn strings and lists
Requirement Analysis:
Read the input from user
Use split function and store in the list
Create an empty list
Compare if it contains alphabet values , if true append to a list by reversing it else append the
actual value without reversing
Print the values in the newlist

Program
s=input("Enter the text :")

52 | P a g e
list1=s.split()
list2=[]
for x in range(0,len(list1)):
if(list1[x].isalpha()==True):
list2.append(list1[x][::-1])
else:
list2.append(list1[x])
for y in list2:
print(y,end=' ')

Output:

Exercise 11 # b
Question
Given a string, the task is to write a program to extract overlapping consecutive string slices
from the original string according to size K. K and string is to be given by user
Objective :
To learn string concepts and functions
Requirement Analysis:
 Read the text from user
 Read the size of text of overlap from user
 Create an empty list
 Compare the overlapping size with string size
 If overlapping size is more the string size show “Invalid k value “ message
 Else append the values from string from I value to i+overlapping size using for loop

53 | P a g e
Program
string=input("Input the string : ")
size=int(input("Enter the size to find overlapping :"))
newlist=[]
if(size>len(string)):
print('Invalid k value')
else:
for i in range(len(string)-size+1):
newlist.append(string[i:i+size])
print(newlist)

Output:

Exercise 11 # c
Question:
Given a string, the task is to write a program to replace every Nth character in a string by the
given value K. String, K and N must be given the user
Objective :
To learn string concepts and built in functions
Requirement Analysis :
 Read the string
 Read the character k and position n
 Check if n is greater than length of the string
 If true print a message “Invalid Input”
 Else
 Process the values to add them in the list and assign the character k to list at the index
 Print the values in the list

54 | P a g e
Program
string=input("Enter string : ")
k=input("Enter the character k : ")
n=int(input("Enter the position n : "))
if(n>len(string)):
print('Invalid input')
else:
l1=[x for x in string]
for i in range(n-1,len(l1),n):
l1[i]=k
for y in l1:
print(y,end='')
Output:

Exercise 12 # a
Question
Write a function called ‘sum_digits’ that is given an integer num and returns the sum of the
digits of num
Objective :
To understand use function concepts
Requirement Analysis :
 Define a function with an input number and return value of sum
 Write the logic of sum of individual digits in the function
 Read the input from user
 Call the function by giving the user input

55 | P a g e
Program
def sum_of_digits(num):
sum1=0
while(num>0):
sum1=sum1+(num%10)
num//=10
return(sum1)

num=int(input("Enter a number :"))


print("Sum of digits :",sum_of_digits(num))

Output:

Exercise 12 # b
Question
Write a function called ‘first_diff’ that is given two strings and returns the first location in which
the strings differ. If the strings are identical, it should return -1
Objective
To learn functions concept and use them
Requirement Analysis :
 Define a function as first_diff with two string inputs
 Write the appropriate logic for finding difference between two string :
 Read the input from user
 Call the function with user input

Program

56 | P a g e
def first_diff(string1,string2):
x=string1.split()
y=string2.split()
if(len(x) < len(y)):
length=len(x)
else:
length=len(y)
for i in range(length):
if x[int(i)] == y[int(i)]:
print("The location of string same")
else:
b=x[i]
print("The location of string different at : ",int(i),"-->",b)

string1="hello you are learning python now"


string2="hello you are good at learning"
first_diff(string1, string2)
Output:

Exercise 12 # c
Question:
Write a function ‘ball_collide’ that takes two balls as parameters and computes if they are
colliding. Your function should return a Boolean representing whether or not the balls are
colliding. [functions] Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius. If
(distance between two balls centers) <= (sum of their radii) then they are colliding
Objective :
To learn and implement function concepts
Requirement Analysis:
 Import math function
 Define the function with three values are tuple . In the function write the formula using
math.sqrt function
 Assign the values for two ball tuples
 Make the function call by giving the values are parameters

57 | P a g e
Program
import math
def ball_collide(ball_tuple1,ball_tuple2):
d=math.sqrt((ball_tuple1[0]-ball_tuple2[0])**2 +

(ball_tuple1[1]-ball_tuple2[1])**2)
if(d<=(ball_tuple1[2]+ball_tuple2[2])):
return True
else:
return False

ball_tuple1=(-2,-2,3)
ball_tuple2=(1,1,3)

collision=ball_collide(ball_tuple1,ball_tuple2)
if(collision):
print("Balls are collide.")
else:
print("Balls are not collide.")
Output:

Exercise 13 # a
Question
Write a program to work with below functions in math module i) cos() ii) ceil() iii) sqrt
Objective:
To learn built in functions of math module
Requirement analysis :
 Import math module
 Apply cos , ceil and sqrt function and print the result

Program
import math
print("Cos 30 is :",math.cos(30))
print("Value after ceil funciton :",math.ceil(4.5867))

58 | P a g e
print("Square of 2 is ",math.sqrt(2))

Output:

Exercise 13 #b
Question :
Write a program to work with below functions in os module i) name ii) getcwd() iii) listdir() –
Objective :
To learn and apply os modules and built in functions
Requirement Analysis:
 Import os module
 Call listdir,getcwd and name using os module
 Print the result

Program

import os

59 | P a g e
path = "/"
dir_list = os.listdir(path)
cwd = os.getcwd()
name=os.name
print("Files and directories in '", path, "' :")
print(dir_list)
print("Current working directory:", cwd)
print("Operating system : ",name)

Output:

Exercise 13 # c
Question:
Write a program to work with below functions in statistics module
i)mean ii)median iii)mode
Objective :
To learn statistics module and built in functions
Requirement Analysis:
Import numpy and scipy
Initialize a list of values
Compute mean using numpy.mean(list) and similarly median and mode
Display the result

60 | P a g e
Program
import numpy
from scipy import stats
speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]
print("Mean : ",numpy.mean(speed))
print("Median : ",numpy.median(speed))
#The mode() method returns a ModeResult object that contains the mode number (86), and
#count (how many times the mode number appeared (3)).
print("Mode : ",stats.mode(speed))
Output:

Exercise 14 # a
Question
Write a python program to illustrate class variable and instance variable for implementing Robot.
In this program the user needs to implement the robots and display the number of robots at each
time
Objective :
To learn classes and objects
Requirement Analysis :
 Create a class Robot
 Define a constructor with name as parameter .Initialize the value in the constructor
 Define a destructor and write the logic to decrease the robot population
 Define a method sayHi and show the appropriate message
 Define a method showmany and show the count of robots

61 | P a g e
 Invoke the functions

Program
class Robot:

population = 0

def __init__(self, name):

self.name = name
print('(Initializing {0})'.format(self.name))
Robot.population += 1

def __del__(self):

print('{0} is being destroyed!'.format(self.name))

Robot.population -= 1

if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots working.'.format(Robot.population))

def sayHi(self):

print('Greetings, my masters call me {0}.'.format(self.name))

def howMany():

print('We have {0:d} robots.'.format(Robot.population))


howMany = staticmethod(howMany)

droid1 = Robot('R1-D1')
droid1.sayHi()
Robot.howMany()

droid2 = Robot('R2-D2')
droid2.sayHi()
Robot.howMany()

print("\nRobots can do some work here.\n")

print("Robots have finished their work. So let's destroy them.")


del droid1

62 | P a g e
del droid2

Robot.howMany()

Output:

Exercise 14 # b
Question
Write a class called Time whose only field is a time in seconds. It should have a method called
convert_to_minutes that returns a string of minutes and seconds formatted as in the following
example: if seconds is 230, the method should return '3:50'.
Objective :
To learn classes and object concepts
Requirement Analysis:
 Create a class time
 Define a constructor to initialize the values
 Define a function convert and write the logic of computing minutes and seconds and
hours
 Create an object and make the function call

63 | P a g e
Program
class Time:
def __init__(self,seconds):
self.seconds=seconds

def convert(self):
self.seconds = self.seconds % (12 * 3600)
hour = self.seconds // 3600
self.seconds %= 3600
minutes = self.seconds // 60
self.seconds %= 60
return "%d:%02d:%02d" % (hour, minutes, self.seconds)

a=Time(230)
print(a.convert())

Output:

Exercise 14 # c
Question
Write a class called Converter. The user will pass a length and a unit when declaring an object
from the class—for example, c = Converter(9,'inches'). The possible units are inches, feet, yards,
miles, kilometers, meters, centimeters, and millimeters. For each of these units there should be a
method that returns the length converted into those units. For example, using the Converter
object created above, the user could call c.feet() and should get 0.75 as the result.
Objective :
To learn classes and objects
Requirement Analysis:
 Create a class converter
 Define a constructor and initialize the values
 Define a function convert and compute the values for conversion

64 | P a g e
 Create the objects and make the function call

Program
class converter:
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def convert(self):
if self.b=='m' and self.c=='cm':
print(self.a*100,'cm')
if self.b=='cm' and self.c=='m':
print(self.a/100,'m')
if self.b=='feet' and self.c=='cm':
print(self.a*30.48,'cm')
if self.b=='cm' and self.c=='feet':
print(self.a/30.48,'feet')
if self.b=='inch' and self.c=='feet':
print(self.a*0.083,'feet')
if self.b=='feet' and self.c=='inch':
print(self.a/0.083)
if self.b=='m' and self.c=='feet':
print(self.a*3.28)
if self.b=='feet'and self.c=='m':
print(self.a/3.28)
if self.b=='km' and self.c=='m':
print(self.a*1000,'m')
if self.b=='m' and self.c=='km':
print(self.a/1000)
if self.b=='km' and self.c=='mm':
print(self.a*10000,'mm')
if self.b=='mm' and self.c=='km':
print(self.a/10000,'km')
if self.b=='miles' and self.c=='km':
print(self.a*1.60,'km')
if self.b=='km' and self.c=='miles':
print(self.a/1.60,'km')

print("Converting 9 inches to feet :")


ob1=converter(9,'inch','feet')
ob1.convert()

print("Converting 5 miles to km :")


ob2=converter(50,'miles','km')
ob2.convert()

65 | P a g e
Output:

Exercise 15 # a
Question
Create a class Person which is having field ‘name’, and its sub class Student consists of a method
nameLength() which returns number of characters in the value assigned to name field
Objective :
To learn classes and object
Requirement Analysis:
 Define a class person
 Define a constructor to initialize the name
 Define and write the function to find length

Program

66 | P a g e
class Person():
def __init__(self,name):
self.name=name
def nameLength(self):
print("Length of the name:%d characters"%(len(self.name)))

p1=Person(input("Enter a string : "))


p1.nameLength()

Output:

Exercise 15 # b
Question :
Create a class College which has a getCollegeName function to display college name and create
child class Department which has setCollegeName, setDepartment and getDepartment functions.
Objective :
To understand and implement inheritance concept
Requirement Analysis:
 Create a class college with a constructor and getmethod to return college name
 Crate a child class Department to inherit from College and design methods : a
constructor , get and set methods
 Create the child object and make the function calls
Program

67 | P a g e
class College:
def __init__(self,cname):
self.cname=cname
def getCollegeName(self):
print("College Name",self.cname)

class Department(College):
def __init__(self,cname,dname):
super().__init__(cname)
self.dname=dname
def getDepartment(self):
print("Department Name :",self.dname)
def setDepartment(self,dname):
self.dname=dname
def setCollegeName(self,cname):
self.cname=cname
c=College("REC")
D=Department("REC","CSE")
D.getDepartment()
D.getCollegeName()

Output:

68 | P a g e
Exercise 15 # c
Question
Create a class called ‘Bank’ which consists of a method getroi(), override getroi() method in it’s
sub classes SBI, ICICI classes to return different rate of interest values.
Objective :
To learn Inheritance
Requirement Analysis:
 Create a class Bank and define a method getroi and return the interest value
 Create a child class ICICI inheriting from Bank and redefine the getroi method to return
interest value
 Create another child class SBI inheriting from Bank and redefine the getroi method to
return interest value
 Create two child objects for SBI and ICICI and make the function call

69 | P a g e
Program
class Bank:
def getroi(self):
return 12
class ICICI(Bank):
def getroi(self):
return 9;

class SBI(Bank):
def getroi(self):
return 7;

ic=ICICI()
sb=SBI()
print("ICICI Rate of Interest :",ic.getroi())
print("SBI Rate of Interest : ",sb.getroi())

Output:

Exercise 16 # a
Question
Write a program to perform addition of two numbers in a try block and wrote except block to
handle ValueError if invalid data is given for input() function
Objective :
To learn Exception handling
Requirement Analysis
 Read two inputs from user
 Place the sum statement under try block
 Use except for ValueError and print the appropriate message
Program
val1=input("Give an input : ")

70 | P a g e
val2=input("Give another input : ")
try:
print("Result is : ",int(val1)+int(val2))
except ValueError as ve:
print("Character conversion with int() is invalid!!")

Output:

Exercise 16 # b
Question
Write a program to find the average of list of numbers given and write exception handling code
with single except block to handle ZeroDivisionError and ValueError
Objective :
To learn Exception handling
Requirement Analysis:
 Read an input in the form a string
 Define the below statements in try block
 Process the values in to list
 Compute the sum and average
 Use except for ValueError and ZeroDivisionError

71 | P a g e
Program
string=input("Enter list of values : ")
nlist=string.split(" ")
try:
numlist=[int(val) for val in nlist]
sumlist=sum(numlist)
print("Average of values is : ",sumlist/len(numlist))
except ValueError:
print("Character conversion with int() is invalid!!")
except ZeroDivisionError:
print("Cannot Divide by zero")

Output:

Exercise 16 # c
Question
Write a program to display an element of a list given by asking an index value from the user and
also write except block to handle IndexError.
Objective :
To learn exception handling
Requirement Analysis :
 Read the input and process the input to list
 Read the index from user
 Put the statement of displaying the value in the try block
 Handle with except IndexError
 Display a proper message

72 | P a g e
Program
string=input("Enter list of values : ")
nlist=string.split(" ")
print("Enter the index to show the value : ")
ind=int(input())
try:

print(nlist[ind] , " is the element at position",ind)

except IndexError:
print("There is no element Index doesn't exists !..")

Output:

73 | P a g e

You might also like