Download as pdf or txt
Download as pdf or txt
You are on page 1of 114

V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.

COMPUTER SCIENCE

PROGRAMMING IN
PYTHON 12
HAND ON PRACTICE & BOOK INSIDE
EXAMPLE PROGRAMS

20-21
Education is the passport to the future, for tomorrow
belongs to those who prepare for it today
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

ACKNOWLEDGEMENT

I owe my thanks to a great many people who helped and


supported me to write this book.

I express my deep and sincere gratitude to Dr.RM.Alagappa


Chettiar Founder of Alagappa Group of Educational Institutions.
I extend my heartfelt and sincere thanks to our beloved Achi-
Dr.Umayal Ramanathan and Dr.Ramanathan Vairavan,
Chairman, for providing all necessary facility.

I extended my reverential gratitude to Mr.G. Naresh Kumar,


Trustee for his valuable suggestions and ideas towards completion of
book successfully and Mrs. K.S. Revati, Principal for her valuable
guidance and support throughout the completion of my task.

It’s my privilege to express my sincere thanks to all the staff


members of Alagappa schools, who guided and inspired me to
complete the book. I also thank all my well wishers and friends who
extended this valuable cooperation by providing all the information
that I needed for this book.

I express my sincere thanks to my family who have helped


and supported me to the journey of my book.
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

ALAGAPPA SCHOOLS, CH-84.


Study Materials -XII STD

COMPUTER SCIENCE

PROGRAMMING IN PYTHON

HAND ON PRACTICE & BOOK INSIDE EXAMPLE


PROGRAMS

Prepared by
DEPARTMENT OF COMPUTER SCIENCE
ALAGAPPA SCHOOLS, CH-84
1.V.Devanathan M.Sc (CS).,M.Phil.,Ph.D., 2. B.Sharmila B.Sc(CS).,B.Ed.,
PGT Computer Science TGT Computer Science
Alagappa Schools Alagappa Schools
Purasaiwalkam Purasaiwalkam
Chennai-84. Chennai-84.
E-mail:vigneshwardeva@gmail.com E-mail:sharmilababu11@gmail.com
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

TABLE OF CONTENT

PAGE
UNIT NO CHAPTER TITLE
NO
1 Function 1
UNIT- I
Problem 2 Data Abstraction nil
Solving 3 Scoping 2
Techniques
4 Algorithmic Strategies nil
Python -Variables and
5 nil
Operators
UNIT- II 6 Control Structures 3
Core
Python 7 Python functions 21
Strings and String
8 35
manipulations
UNIT-III Lists,Tuples,Sets and
9 49
Modularity Dictionary
and OOPS 10 Python Classes and objects 62
11 Database Concepts nil
UNIT-IV Structured Query Language
Database 12 82
(SQL)
concepts
and MySql 13 Python and CSV files 87
Importing C++ programs in
14 91
UNIT-V Python.
Integrating Data manipulation through
15 99
Python with SQL
MySql and Data visualization using pyplot:
C++ 16 line chart, pie chart and bar 106
chart
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

CHAPTER 1
FUNCTION
HANDS ON EXPERIENCE:

1.Write algorithmic function definition to find the minimum among 3


numbers.

2.Write algorithmic recursive function definition to find the sum of n


natural numbers.

1
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

CHAPTER 3
SCOPING
HANDS ON PRACTICE:

1. Observe the following diagram and write the pseudo code for
the following.

2
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

CHAPTER 6
CONTROL STRUCTURES

HANDS ON EXPERIENCE:

1. Write a program to display


A
A B
ABC
ABCD
ABCDE
Coding:

Output:

3
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

2. Write a program to display multiplication table for a given number

Coding:

Output:

4
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

3. Write a program to display all 3 digit odd numbers(5 m)

Coding

Output:

5
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

4. Write a program to check whether the given character is a vowel or


not

Coding:

Output :

5. Using if..else..elif statement check smallest of three numbers

Coding:

Output:

6
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

6. Write a program to check if a number is positive, negative or zero

Coding:

Output:

7. write a program to display Fibonacci series 0 1 2 3 4 5 …….(upto


n terms)

Coding:

Output:

7
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

8. Write a program to display sum of natural numbers, upto n

Coding:

Output:

9. Write a program to check if the given number is a palindrome or


not.

Coding:

Output:

8
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

10. Write a program to print the following pattern

*****
****
***
**
*
Coding:

Output:

11. Write a program to check if the year is leap year or not.

Coding:

Output:

9
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

12. Using if else elif statement write a suitable program to display


largest of 3
numbers.

Coding:

13.Write a program to check whether the given character is a vowel


or not

Coding:

Output :

10
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

14. Using if..else..elif statement check smallest of three numbers

Coding:

Output:

11
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

EXAMPLE-PROGRAMS

1.Program to print your name and address - example for sequential


statement.

Coding:

Output:

2.Program to check the age and print whether eligible for voting.
Coding:

Output:

12
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

3.Program to check if the accepted number odd or even.


Coding:

Output:

4.Program to check if the accepted number is odd or even(using


alternate method of if...else)
Coding:

Output:

13
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

5. Program to illustrate the use of nested if statement

Coding:

Output:

14
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

6. Program to illustrate the use of ‘in’ and ‘not in’ in if statement.

Coding:

Output:

7.Program to illustrate the use of while loop - to print all numbers


from 10 to 15.

Coding:

Output:

15
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

8.Program to illustrate the use of while loop - with else part.

Coding:

Output:

9.Program to illustrate the use of for loop - to print single digit even
number.
Coding:

Output:

2468

16
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

10.Program to illustrate the use of for loop - to print single digit even
number with else part

Coding:

Output:

11.Program to calculate the sum of numbers 1 to 100.

Coding:

Output:

12.Program to illustrate the use of string in range() of for loop.

Coding:

Output:

17
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

13.Program to illustrate the use nested loop -for within while loop.

Coding:

Output:

14.Program to illustrate the use of break statement inside for loop.

Coding:

Output:

Jump stat

18
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

15.Program to illustrate the use of break statement inside for loop.

Coding:

Output:

16.Program to illustrate the use of continue statement inside for loop.

Coding:

Output:

19
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

17.Program to illustrate the use of pass statement.

Coding:

Output:

18.Program to illustrate the use of pass statement in for


loop.
Coding:

Output:

20
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

LESSON-7
PYTHON FUNCTIONS

HANDS ON EXPERIENCE:

1. Write a python code to check whether a given year is leap year or


not
Coding:

Output 1:

Output 2:

21
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

2. Write a python code to find the L.C.M of two numbers.

Coding:

Output:

22
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

23
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

24
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

EXAMPLE-PROGRAMS

1. Program to illustrate the use of simple function to display the given


string.

Coding:

Output:

Hello python

2. Program to illustrate the use of simple function to display the given


string by using alternative method of calling function within the
print() function.

Coding:

Output:

25
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

3. Program to illustrate that defines a function that helps to pass


parameters into the function.

Coding:

Output:

15

4. Program to illustrate that Required Arguments passed to a


function.

Coding:

Output:

26
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

5. Program to illustrate that Required Arguments in Improper order.

Coding:

Output:

6. Program to illustrate that Required Arguments in unexpected


keyword.

Coding:

Output:

27
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

7. Program to illustrate that the parameters orders are changed.

Coding:

Output:

8. Program to illustrate that the default Arguments are passed.

Coding:

Output:

28
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

9. Program to illustrate that we pass more than 3 arguments in the


sum() function.

Coding:

Output:

10. Program to illustrate that the variable-length arguments function.

Coding:

Output

:
29
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

11. Program to illustrate that to use the Anonymous function


[LAMBDA]

Coding:

Output:

12. Program to illustrate that to use the Return statement.

Coding:

Output:

30
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

13. Program to illustrate that to create a local variable.

Coding:

Output:

14. Program to illustrate that to accessing Global Variable from


inside a function.

Coding:

Output:

31
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

15. Program to illustrate that to modifying Global Variable from


inside the function.

Coding:

Output:

16. Program to illustrate that to changing Global Variable from inside


a function using Global keywords.

Coding:

Output:

32
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

17. Program to illustrate that to use Global Variables and Local


Variables in same code.

Coding:

Output:

18. Program to illustrate that to use Global Variables and Local


Variables in same name.

Coding:

Output:

33
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

19. Program to illustrate that to use Function input() and apply eval()
function.

Coding:

20. Program to illustrate that Recursive function used to calculate


factorial of the given number.

Coding:

Output:

34
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Lesson 8
STRINGS AND STRINGS MANIPULATION
HANDS ON EXPERIENCE:

1.What will be the output of the following python code?

Coding:

Output:

2. Write a python program to find the length of a string.

Coding:

Output:

35
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

3. Write a program to print integers with ‘*’ on the right of specified


width

Coding:

Output:

4. Write a python program to display the given pattern.


COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C
Coding:

Output:

36
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

5. Write a program to add a prefix text to all the lines in a string

Coding:

Output:

37
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

6. Write a program to create a mirror of the given string. For


example,”wel”=”lew”

Coding:

Output:

7. Write a program to remove all the occurrences of a given character


in a string.

Coding:

Output:

38
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

8. Write a program to append a string to another string without using


+= operator

Coding:

Output:

9.Write a program to swap two strings.

Coding:

Output:

39
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

10. Write a program to replace a string with another string without


using replace()

Coding:

Output:

11. Write a program to count the number of characters words and lies
in a given string.

Coding:

Output:

40
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

EXAMPLE-PROGRAMS
1. Program to access each character with its positive subscript of a
giving string.

Coding:

Output:

2. Program to access each character with its negative subscript of a


giving string.

Coding:

Output:

41
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

3. Code lines to delete a particular character in a string.

Coding:

Output:

4.Code lines to delete a stringvariable.

Coding:

Output:

42
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

5.Program to slice substrings using for loop.

Coding:

Output

6.Stride when slicing string.

Coding:

Output

43
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

7. Example forthe format( ) function.

Coding:

Output:

8.Example for the Membership Operators.

Coding:

Output

44
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

9. Program to check whether the given string is palindrome or not.

Coding:

Output

45
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

10. Program to display the following pattern.


*
**
***
****
*****
Coding:

Output:

11. Program to display the number of vowels and consonants in the


given string.

Coding:

Output:

46
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

12. Program to create an Abecedarian series. (Abecedarian refers list


of elements appear in alphabetical order)

Coding:

Output:

13.Program that accept a string from the user and display the same
after removing vowels from it.

Coding:

Output:

47
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

14. Program that count the occurrences of a character in a string.

Coding:

Output:

48
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Lesson 9
LISTS,TUPLES,SETS AND DICTIONARY
HANDS ON EXPERIENCE:

1. What will be the value of x in following python code?

Coding:

Output:

2. What will be the output of the following code?

Coding:

Output:

49
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

3. Write a program to remove duplicate from a list.

Coding:

Output:

4.Write a program that prints the maximum value in a Tuple.

Coding:

Output:

5. Write a program that finds the sum of all the numbers in a tuples
using while loop.

Coding:

Output:
57
50
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

6.Write a program that finds sum of all even numbers in a list.

Coding:

Output:

7.Write a program that reverse a list using a loop.


Coding:

Output:

8. Write a program to insert a value in a list at the specified location.


Coding:

Output:

51
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

10. Write a program that creates a list of numbers from 1 to 50 that


are either divisible by 3 or divisible by 6.

Coding:

Output:

11. Write a program to create a list of numbers in the range 1 to 20.


Then delete all the numbers from the list that are divisible by3

Coding:

Output:

52
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

12. Write a program that counts the number of times a value appears
in the list. Use a loop to do the same

Coding:

Output:

13. Write a program that prints the maximum and minimum value in
a dictionary.

Coding:

Output:

53
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

EXAMPLE-PROGRAMS

1. Python program to update/change single value.

Coding:

Output:

54
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

2. Python program to update/change range of values.

Coding

Output

3.Program that creates a list of numbers from 1 to 20 that are


divisible by 4.

Coding

Output:

55
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

4. Program to define a list of countries that are a member of BRICS.


Check whether a county is member of BRICS or not.

Coding:

Output:

56
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

5. Python program to read prices of 5 items in a list and then display


sum of all the prices, product of all the prices and find the average.

Coding:

Output:

57
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

6. Program to create a list of numbers in the range 1 to 10. Then delete


all the even numbers from the list and print the final list.
Coding:

Output:

7.Program to generate in the Fibonacci series and store it in a list.


Then find the sum of all values.
Coding:

Output:

58
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

8. Program to return the maximum as well as minimum values in a


list.

Coding:

Output:

9. Program to swap two values using tuple assignment.

Coding:

Output:

59
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

10. Program using a function that returns the area and circumference
of a circle whose radius is passed as an argument.two values
using tuple assignment.

Coding:

Output:

11.Program that has a list of positive and negative numbers. Create a


new tuple that has only positive numbers from the list.

Coding:

Output:

60
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

12. Program to access all the values stored in a dictionary.

Coding:

Output:

61
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Lesson 10
PHYTHON CLASSES AND OBJECTS
HANDS ON EXPERIENCE:

1. What is the output of the following program?


Coding:

Output:

2.Write a program using class to accept three sides of a triangle and


print its area.
Coding:

Output:

62
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

3. Find the error in the following program to get the given output
Coding:

Output:

4. What is the output of the following program?


Coding:

Output:

63
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

5. Write a menu driven program to add or delete stationary items.


You should use dictionary to store items and the brand.

Coding:

64
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Output:

65
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

6. Write a program using class to store name and marks of students in


list and print total marks.

Coding:

Output:

66
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

7. Write a menu driven program to read, display, add and subtract


two distances.

Coding:

67
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Output:

68
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

EXAMPLE-PROGRAMS

1.Program to define a class and access its member variables.

Coding:

Output:

2.Program to find total and average marks using class.

Coding:

Output:

69
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

3. Program to check and print if the given number is odd or even


using class.

Coding:

Output:

4. Program to illustrate Constructor.

Coding:

Output:

70
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

5. Program to illustrate class variable to keep count of number of


objects created.

Coding:

Output:

71
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

6. Program to illustrate about the del ( ) method.


Coding:

Output:

7. Program to illustrate private and public variables.


Coding:

Output

72
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

8. Program to calculate area and circumference of a circle.

Coding:

Output:

73
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

9. Program that keeps record of books available in you school library.

Coding:

74
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Output:

75
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

76
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

10. Program to accept a string and print the number of uppercase,


lowercase, vowels, consonants and spaces in the given string.

Coding:

77
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Output:

78
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

11. Program to store product and its cost price. Display all the
available products and prompt to enter quantity of all the products.
Finally generate a bill which displays the total amount to be paid.

Coding:

79
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

80
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Output:

81
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

CHAPTER 12
STRUCTURED QUERY LANGUAGE

HANDS ON EXPERIENCE:

1. Create a query of the student table in the following order of fields


name, age,place and admno.
CREATE TABLE student(name char(20), age integer, place
char(15),
admno integer not null primary key);

2. Create a query to display the students table with students of age


more than 18 with unique city.
Select * from student where age>=18 group by place;(or)
Select * from student where age>=18 and place=”Coimbatore”;

82
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

3. Create a employee table with the following fields employee


number,employee name, designation, date of joining and basic pay.
Create Table employee(empno integer, ename char(30), desig
char(20), doj datetime, basic integer);

4. In the above table, set the employee number as primary key and
check for NULL values in any field.
Alter table employee modify empno integer NOT NULL PRIMARY
KEY;

83
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

5. Prepare list of employees who are Managers.


Select * from employee where desig=”Manager”;

6. Consider the following employee table. Write SQL Commands for


the qtns(i) to (v).

i) To display the details of all employees in descending order of pay.


Select * employees order by pay desc;

84
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

ii) To display all employees whose allowance is between 5000 and


7000.Select * from employees where allowance>=5000 and
allowance<=7000;

iii) To remove the employees who are mechanic.


Delete from employees where desig=’Mechanic’;

iv) To add a new row


Insert into employees(empcode, ename, desig, pay, allowance)
85
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

values(‘A1005’,’Balaguru’,’Engineer’,30000,15000);

v) To display the details of all employees who are operators.


Select * from employees where desig=’Operator’;

7. Write a SQL Statement to create a table for employee having any


five fields and create a table constraint for the employee table.

Create table Employee( empcode char(10) not null, ename char(30),


design char(20), pay integer, allowance integer, PRIMARY
KEY(empcode));

86
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

CHAPTER 13

PYTHON AND CSV FILES

HANDS ON EXPERIENCE:

1. Write a python program to read the following Namelist.csv file and


sort the data in alphabetical order of names in a list and display the
output.

Program:

import csv, operator


ifile="c:\\pyprg\\namelist.csv"
f=open(ifile,'r')
reader=csv.reader(f)
next(reader)
sortedlst=sorted(reader,key=operator.itemgetter(1))
for r in sortedlst:
print(r)
f.close

87
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Output:

['2', 'ADHITH', 'DOCTOR']


['5', 'BINDHU', 'LECTURER']
['3', 'LAVANYA', 'SINGER']
['1', 'NIVETHITHA', 'ENGINEER']
['4', 'VIDHYA', 'TEACHER']

2. Write a python program to accept the name and five subjects


marks of 5 students. Find the total and store all the details of the
students in a CSV file.
import csv
lstheader=['Sl.no','Name','Tamil','English','Maths','Science','Social','T
otal']
with open('c:\\pyprg\\students.csv','w') as f:
w=csv.writer(f)
w.writerow(lstheader)
for i in range(5):
total=0
marks=[]
name=input("Enter Name")
print("Enter marks in 5 subjects")
for j in range(5):
m=input()
marks.append(m)
total=total+int(m)
w.writerow([i+1,name,marks[0],marks[1],marks[2],marks[3],marks[4
],total])
f.close
f=open('c:\\pyprg\\students.csv','r')
reader=csv.reader(f)
for row in reader:
print(row)
f.close
88
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Output:
Enter NameGanesh
Enter marks in 5 subjects
78
89
96
95
87
Enter Name Ramesh
Enter marks in 5 subjects
56
55
45
67
70
Enter Name Rakesh
Enter marks in 5 subjects
70
65
87
90
77
Enter Name Rahul
Enter marks in 5 subjects
98
98
100
100
100
Enter Name Suresh
Enter marks in 5 subjects
58
65
67
89
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

76
56
['Sl.no', 'Name', 'Tamil', 'English', 'Maths', 'Science', 'Social', 'Total']
[]
['1', 'Ganesh', '78', '89', '96', '95', '87', '445']
[]
['2', ' Ramesh', '56', '55', '45', '67', '70', '293']
[]
['3', ' Rakesh', '70', '65', '87', '90', '77', '389']
[]
['4', ' Rahul', '98', '98', '100', '100', '100', '496']
[]
['5', ' Suresh', '58', '65', '67', '76', '56', '322']
[]

90
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

CHAPTER 14

IMPORTING C++ PROGRAMS IN PYTHON

HANDS ON EXPERIENCE:

1. Write a C++ program to create a class called Student with the


following details
Protected member
Rno integer
Public members
void Readno(int); to accept roll number and assign to Rno
void Writeno(); To display Rno.
The class Test is derived Publically from the Student class contains
the following
details
Protected member
Mark1 float
Mark2 float
Public members
void Readmark(float,float); To accept mark1 and mark2
void Writemark(); To display the marks
Create a class called Sports with the following detail
Protected members
score integer
Public members
void Readscore(int); To accept the score
void Writescore(); To display the score
The class Result is derived Publically from Test and Sports class
contains the
following details
Private member
Total float
91
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Public member
void display() assign the sum of mark1 ,mark2,score in total.
invokeWriteno(),Writemark() and Writescore()
Display the total also.
Save the c++ program in afile called hybrid. Write a python
program to
execute the hybrid.cpp
Procedure:
Open notepad and type the following code and save it as hybrid.cpp

#include<iostream>
using namespace std;
class Student
{
protected:
int Rno;
public:
void Readno(int r)
{
Rno=r;
}
void Writeno()
{
cout<<"\nRoll no : "<<Rno;
}
};
class Test :public Student
{
protected:
float Mark1,Mark2;
public:
void Readmark (float m1,float m2)
{
Mark1=m1;
92
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Mark2=m2;
}
void Writemark()
{
cout<<"\n\n\tMarks Obtained\n ";
cout<<"\n Mark1 : "<<Mark1;
cout<<"\n Mark2 : "<<Mark2;
}
};
class Sports
{
protected:
int score;// score = Sports mark
public:
void Readscore (int s)
{
score=s;
}
void Writescore()
{
cout<<"\n Sports Score : "<<score;
}
};
class Result :public Test,public Sports
{
int Total;
public:
void display()
{
Total = Mark1 + Mark2 + score;
Writeno();
Writemark();
Writescore();
cout<<"\n\n Total Marks Obtained : "<< Total<<endl;
93
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

}
};
int main()
{
Result stud1;
stud1.Readno(1201);
stud1.Readmark(93.5,95);
stud1.Readscore(80);
cout<<"\n\t\t\t HYBRID INHERITANCE PROGRAM\n";
stud1.display();
return 0;
}
Now type the python program in new notepad file and name it as
hybrid.py
import sys, os, getopt
def main (argv):
cpp_file=''
exe_file=''
opts, args=getopt.getopt(argv,"i:",['ifile='])
for o, a in opts:
if o in("-i","--ifile"):
cpp_file=a+'.cpp'
exe_file=a+'.exe'
run(cpp_file,exe_file)
def run(cpp_file,exe_file):
print("Compiling "+cpp_file)
os.system('g++ '+ cpp_file +' -o '+exe_file)
print("Running "+exe_file)
print(" ------ ")
print
os.system(exe_file)
print
if name ==' main ':
main(sys.argv[1:])
94
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

In command prompt, type the following


python c:\pyprg\hybrid.py –i c:\pyprg\hybrid

Output:

2. Write a C++ program to print boundary elements of a matrix and


name the file as Border.cpp. Write a python program to execute the
border.cpp.

Open notepad and type the following program and save it as


Border.cpp

#include <iostream>
using namespace std;
void printBoundary (int a[][10], int m, int n)
{
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
{
95
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

if (i==0|| j==0||i==m-1||j==n-1
cout<<a[i][j]<<" ";
else
cout<<" ";
}
cout <<endl ;
}
}
int main()
{
int a[10][10] ,i,j,m,n;
cout<<"Enter more than 3 x3 "<<endl;
cin>>m>>n;
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
cout<<"enter the values for array”;
cin>>a[i][j];
}
}
system("cls");
cout<<"\n\nOriginal Array\n";
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<"\n\n The Boundry element\n";
printBoundary(a, m, n);
return 0;
96
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

}
Open notepad and type the following code and save as border.py
import sys, os, getopt
def main (argv):
cpp_file=''
exe_file=''
opts, args=getopt.getopt(argv,"i:",['ifile='])
for o, a in opts:
if o in("-i","--ifile"):
cpp_file=a+'.cpp'
exe_file=a+'.exe'
run(cpp_file,exe_file)
def run(cpp_file,exe_file):
print("Compiling "+cpp_file)
os.system('g++ '+ cpp_file +' -o '+exe_file)
print("Running "+exe_file)
print(" ------ ")
print
os.system(exe_file)
print
if name ==' main ':
main(sys.argv[1:])
In command prompt type the following
Python c:\pyprg\border.py –i c:\pyprg\border

97
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Output:

98
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

CHAPTER 15

DATA MANIPULATION THROUGH SQL

HANDS ON EXPERIENCE:

1. Create an interactive program to accept the details from the user


and store it in csv file using python for the following table.
Database name: DB1
Table name: Customer

Program:

import sqlite3
import io
import csv
d=open('c:\\pyprg\\sql.csv','w')
c=csv.writer(d)
con=sqlite3.connect("db1.db")
cursor=con.cursor()
cursor.execute("Drop table customer")
cursor.execute("Create table customer(cust_id char(5),cust_name
char(30),
address char(50), phone_no integer, city char(20));")

99
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

print("Enter 3 customer details")


print("Enter 3 customer ids")
cid=[input() for i in range(3)]
print("Enter 3 customer names")
cname=[input() for i in range(3)]
print("Enter 3 address")
cadd=[input() for i in range(3)]
print("Enter 3 phonenos")
cphno=[input() for i in range(3)]
print("Enter 3 cities")
city=[input() for i in range(3)]
for i in range(3):
cursor.execute("Insert into customer values(?,?,?,?,?)",
(cid[i],cname[i],cadd[i],cphno[i],city[i]))
cursor.execute("Select * from customer")
co=[i[0] for i in cursor.description]
c.writerow(co)
data=cursor.fetchall()
for row in data:
c.writerow(row)
d.close()
cursor.close()
con.close()

Output:

Enter 3 customer details


Enter 3 customer ids
C008
C010
C012
Enter 3 customer names
Sandeep
Anurag Basu
100
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Hrithik
Enter 3 address
14/1 Pritam Pura
15A, Park Road
7/2 Vasant Nagar
Enter 3 phonenos
41206819
61281921
26121949
Enter 3 cities
Delhi
Kolkata
Delhi
2. Consider the following table GAMES. Write a python program to
display the records for question i) to iv) and give output for SQL
queries v) to viii)
Table Games

Program to create database and Table:


import sqlite3
conn=sqlite3.connect("games.db")
cursor=conn.cursor()
cursor.execute("Drop table games")
cursor.execute("Create table games (Gcode integer Primary Key Not
Null,Name
char(30), Gamename char(30), number integer, prizemoney integer,
ScheduleDate
101
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

Date);")
game_data=[(101,'Padmaja','Carom Board',2,5000, '2014-01-23'),
(102,'Vidhya','Badminton',2,12000,'2013-12-12'),
(103,'Guru','Table Tennis',4,8000,'2014-02-14'),
(105,'Keerthana','Carom Board',2,9000,'2014-01-01'),
(108,'Krishna','Table Tennis',4,25000,'2014-03-19')]
for row in game_data:
format_str="""Insert into games
values("{GC}","{name}","{Gname}","{num}","{Pmoney}","{Sdate
}");"""
sql_command=format_str.format(GC=row[0],name=row[1],Gname=
row[2],num=r
ow[3],Pmoney=row[4],Sdate=row[5])
cursor.execute(sql_command)
conn.commit()
conn.close()
i) To display the names of all Games with their Gcodes in descending
order of their schedule date.

Program :

import sqlite3
conn=sqlite3.connect("Games.db")
cursor=conn.cursor()
cursor.execute("Select Gamename, Gcode from Games order by
Scheduledate
desc;")
res=cursor.fetchall()
print(*res,sep="\n")
conn.close()

Output:
('Table Tennis', 108)
('Table Tennis', 103)
102
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

('Carom Board', 101)


('Carom Board', 105)
('Badminton', 102)

ii) To display the details of those games which are having prize
money more than 7000

Program:

import sqlite3
conn=sqlite3.connect("games.db")
cursor=conn.cursor()
cursor.execute("select * from games where prizemoney>7000;")
res=cursor.fetchall()
print(*res,sep='\n')
conn.close()

Output:
(102, 'Vidhya', 'Badminton', 2, 12000, '2013-12-12')
(103, 'Guru', 'Table Tennis', 4, 8000, '2014-02-14')
(105, 'Keerthana', 'Carom Board', 2, 9000, '2014-01-01')
(108, 'Krishna', 'Table Tennis', 4, 25000, '2014-03-19')

iii) To display the names and game names of the players in ascending
order of game name.

Program:

import sqlite3
conn=sqlite3.connect("games.db")
cursor=conn.cursor()

103
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

cursor.execute("select name, Gamename from games order by


gamename")
res=cursor.fetchall()
print(*res,sep='\n')
conn.close()

Output:
('Vidhya', 'Badminton')
('Padmaja', 'Carom Board')
('Keerthana', 'Carom Board')
('Guru', 'Table Tennis')
('Krishna', 'Table Tennis')

iv) To display sum of prizemoney for each of the number of


participation groupings

Program:

import sqlite3
conn=sqlite3.connect("games.db")
cursor=conn.cursor()
cursor.execute("select sum(number*prizemoney) from games")
res=cursor.fetchall()
print(*res,sep='\n')
conn.close()

Output:

(184000,)

104
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

v) Display all the records based on Gamename

Program:

import sqlite3
conn=sqlite3.connect("games.db")
cursor=conn.cursor()
cursor.execute("select * from games order by gamename")
res=cursor.fetchall()
print(*res,sep='\n')
conn.close()

Output:
(102, 'Vidhya', 'Badminton', 2, 12000, '2013-12-12')
(101, 'Padmaja', 'Carom Board', 2, 5000, '2014-03-01')
(105, 'Keerthana', 'Carom Board', 2, 9000, '2014-01-01')
(103, 'Guru', 'Table Tennis', 4, 8000, '2014-02-14')
(108, 'Krishna', 'Table Tennis', 4, 25000, '2014-03-19')

105
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

CHAPTER – 16

DATA VISUALIZATION USING PYPLOT

HANDS ON EXPERIENCE:

1. Create a plot. Set the title, x and y labels for both axes.
Program:
import matplotlib.pyplot as plt
x=[2,4,5]
y=[5,7,8]
plt.plot(x,y)
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Line graph')
plt.show()

Output:

106
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

2. Plot pie chart for your mark in the recent examination.


Program:
import matplotlib.pyplot as plt
sizes=[90,95,87,77,85]
labels=["Tamil","English","Maths","Science","Social"]
plt.pie(sizes,labels=labels, autopct="%.2f")
plt.axes().set_aspect("equal")
plt.show()

Output:

3. Plot a line chart on the academic performance of class 12 students


in Computer Science for the past 10 years.

Program:
import matplotlib.pyplot as plt
years=[2010, 2011,2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019]
avg=[85, 86, 88, 89, 86, 87, 89, 90, 92, 94]
plt.plot(years,avg)
107
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

plt.title("Computer Science Academic Performance")


plt.xlabel("Years")
plt.ylabel("Average Marks")
plt.show()
Output:

4. Plot a bar chart for the number of computer science periods in a


week.
Program:
import matplotlib.pyplot as plt
daylabels=["Mon","Tue","Wed","Thu","Fri", "Sat"]
108
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

periods=[1,2,2,3,2,1]
y_positions=range(len(daylabels))
plt.bar(y_positions,periods)
plt.xticks(y_positions,daylabels)
plt.ylabel("Periods")
plt.title("No.of. Computer Science Periods")
plt.show()

Output:

109
V.Devanathan M.Sc (CS)., M.Phil., Ph.D., B.Sharmila B.Sc(CS).,B.Ed.,

5. Write the plot for the following pie chart output.

Program:
import matplotlib.pyplot as plt
slices=[7,2,2,13]
activities=['sleeping','eating', 'working','playing']
cols=['c','m','r','b']
plt.pie(slices, labels=activities, colors=cols,startangle=90,
shadow=True,
explode=(0,0,0.1,0),autopct='%1.1f%%')
plt.title('Interesting Graph \nCheck it out')
plt.show()

Calculation for the slices:


29.2
100 x 24 = 7 [ since 24 hours a day]
8.3
100 x 24 = 1.99 =2
54.2
100 x 24 = 13 so the slices be [7,2,2,13]
110

You might also like