0% found this document useful (0 votes)
3 views211 pages

Python Course File

Uploaded by

mknizamsiith
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views211 pages

Python Course File

Uploaded by

mknizamsiith
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

GITAM SCHOOL OF TECHNOLOGY,

HYDERABAD CAMPUS
(Declared as deemed-to-be-University u/s 3 of the UGC Act, 1956)
Department of Computer Science and Engineering

Name of the course: Python Programming

Course code : CSEN1021

Academic Year: 2023-24


Index

[Link] Description
1 Course Objective
2 Course Outcome
3 Syllabus
4 Textbooks
5 Academic calendar
6 Time table
7 Course Plan
8 Evaluation plan
9 Process
10 Assessment Dates
11 Material
12 Question bank
13 Slow learners
14 Remedial Class Details
15 Attendance
16 Feedback
17 Minutes of meeting
18 End Sem Marks
19 Co -Po mapping
GITAM (Deemed to be University) GITAM School of Technology
L T P S J C
CSEN1021 PROGRAMMING WITH PYTHON
0 0 6 0 0 3
Pre-requisite None
Co-requisite None
Preferable Familiarity with Computer system and its operation.
exposure

Course Educational objectives:


1. To elucidate problem solving through python programming language
2. To introduce function-oriented programming paradigm through python
3. To train in development of solutions using modular concepts
4. To teach practical Python solution patterns

Unit I: Introduction to Python 18 Hours


Python – Numbers, Strings, Variables, operators, expressions, statements, String operations,
Math function calls, Input/output statements, Conditional If, while and for loops.
Exercises:

1. Accept input from user and store it in variable and print the value.
2. Use of print statements and use of (.format )for printing different data types.
3. Take 2 numbers as user input and add, multiply, divide, subtract, remainder and print
the output (Same operations on floating point input as well)
4. Conversion of one unit to another (such as hours to minutes, miles to km and etc)
5. Usage of mathematical functions in python like [Link], floor, fabs, fmod, trunc,
pow, sqrt etc.
6. Building a mathematical calculator that can perform operations according to user
input. Use decision making statement.
7. Accepting 5 different subject marks from user and displaying the grade of the student.
8. Printing all even numbers, odd numbers, count of even numbers, count of odd
numbers within a given range.
9. a) Compute the factorial of a given number. b) Compute GCD of two given numbers.
c) Generate Fibonacci series up to N numbers.
10. Check whether the given input is a) palindrome b) strong c) perfect
11. Compute compound interest using loop for a certain principal and interest amount

B Tech. Computer Science and Engineering w.e.f. 2023-24 admitted batch


GITAM (Deemed to be University) GITAM School of Technology

Unit II: Functions 18 Hours

User defined Functions, parameters to functions, recursive functions. Lists, Tuples,


Dictionaries, Strings.

Exercises:
● Create a function which accepts two inputs from the user and compute nCr
● Recursive function to compute GCD of 2 numbers
● Recursive function to find product of two numbers
● Recursive function to generate Fibonacci series
● Program to print a specified list after removing the 0th, 4th and 5th elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White', 'Black']
● Program to get the difference between the two lists.
● Program to find the second smallest number and second largest number in a
list.
● Given a list of numbers of list, write a Python program to create a list of tuples
having first element as the number and second element as the square of the
number.
● Given list of tuples, remove all the tuples with length K.
Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K = 2
Output : [(4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
Explanation : (4, 5) of len = 2 is removed.
● Program to generate and print a dictionary that contains a number (between
1 and n) in the form (x, x*x).
Sample Input: (n=5) :
Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
● Program to remove a key from a dictionary
● Program to get the maximum and minimum value in a dictionary.
● Program to perform operations on string using unicodes ,splitting of string,accessing
elements of string using locations
● Program for Counting occurrence of a certain element in a string, getting indexes that
have matching [Link] ex -.In Rabbit count how many times b has occurred .
Example-I have to go to a doctor and get myself checked. Count the number of
occurrences of ‘to’.
● Program for replacing one substring by another For example - Rabbit - Replace ‘bb’ by
‘cc’
● Program to Acronym generator for any user input (ex-input is Random memory access
then output should be RMA).Example - Random number (RN)
● Python function that accepts a string and calculates the number of uppercase
letters and lowercase letters.
● Program to count the number of strings where the string length is 2 or more
and the first and last character are same from a given list of strings
Sample List : ['abc', 'xyz', 'aba', '1221'] Expected Result : 2

B Tech. Computer Science and Engineering w.e.f. 2023-24 admitted batch


GITAM (Deemed to be University) GITAM School of Technology

Unit III: Files and Packages 18 Hours


Files—Python Read Files, Python Write/create Files, Python Delete Files.
Pandas -- Read/write from csv, excel, json files, add/ drop columns/rows,
aggregations, applying functions.
Exercises
● read an entire text file.
● read the first n lines of a file.
● append text to a file and display the text.
● Read numbers from a file and write even and odd numbers to separate files.
● Count characters, words and lines in a text file.
● To write a list to a file.
● Given a CSV file or excel file to read it into a data frame and display it.
● Given a data frame, select rows based on a condition.
● Given is a data frame showing the name, occupation, salary of people. Find the
average salary per occupation.
● To convert Python objects into JSON strings. Print all the values.
● Write a Pandas program to read specific columns from a given excel file.

Unit IV: Operations in database with suitable libraries 18 Hours


SQLite3: CRUD operations (Create, Read, Update, and Delete) to manage data stored in a
database.
Matplotlib -- Visualizing data with different plots, use of subplots. User defined packages,
define test cases.

Exercises
Special commands to sqlite3 (dot-commands)
Rules for "dot-commands"
Changing Output Formats
Querying the database schema
Redirecting I/O
Writing results to a file
Reading SQL from a file
File I/O Functions
The edit() SQL function
Importing CSV files
Export to CSV
Export to Excel
Reference - [Link]

Matplotlib can be practiced by considering a dataset and visualizing it.


It is left to the instructor to choose appropriate dataset.

B Tech. Computer Science and Engineering w.e.f. 2023-24 admitted batch


GITAM (Deemed to be University) GITAM School of Technology
Unit V: Regular Expressions 18 Hours

Regular expression: meta character, regEx functions, special sequences, Web


scrapping, Extracting data.

Exercises

Write a Python program to check that a string contains only a certain set of characters (in this
case a-z, A-Z and 0-9).
Write a Python program that matches a string that has an a followed by zero or more b's
Write a Python program that matches a string that has an a followed by one or more b's
Write a Python program that matches a string that has an a followed by zero or one 'b'
Write a Python program that matches a string that has an a followed by three 'b'
Write a Python program to find sequences of lowercase letters joined with an underscore

Write a Python program to test if a given page is found or not on the server.
Write a Python program to download and display the content of [Link] for
[Link].
Write a Python program to get the number of datasets currently listed on [Link]
Write a Python program to extract and display all the header tags from
[Link]/wiki/Main_Page
.
Textbooks(s)
1. Programming with python, T R Padmanabhan, Springer
2. Python Programming: Using Problem Solving Approach, Reema
Thareja, Oxford University Press
Reference Book(s)
1. Programming with python, T R Padmanabhan, Springer
2. Python Programming: Using Problem Solving Approach, Reema Thareja,
Oxford University Press
3. Python for Data Analysis, Wes McKinney, [Link]

Course Outcomes:
After completion of this course the student will be able to
• Define variables and construct expressions.
• Utilize arrays, storing and manipulating data.
• Develop efficient, modular programs using functions.
• Write programs to store and retrieve data using files.

B Tech. Computer Science and Engineering w.e.f. 2023-24 admitted batch


GITAM (Deemed to be University) GITAM School of Technology

CO-PO Mapping:
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO1 PO1 PS1 PSO PSO PSO
0 1 2 1 2 3

CO1 2 3 2 1 2 2 3 2 2
CO2 2 2 2 1 2 2 2 2 2
CO3 2 3 2 1 2 2 2 2 2
CO4 2 3 2 1 2 2 3 2 2
CO5 2 2 2 1 2 2 2 2 2

Note: 1 - Low Correlation 2 - Medium Correlation 3 - High Correlation

APPROVED IN:
BOS : September 6, 2021 ACADEMIC COUNCIL: 21st AC(September 17, 2021)

SDG No. & Statement: 4 Quality Education


Ensure inclusive and equitable quality education and promote lifelong learning opportunities for
all.
SDG Justification:
Learning a programming language like Python students can get decent jobs in different fields.

B Tech. Computer Science and Engineering w.e.f. 2023-24 admitted batch


ACADEMIC CALENDAR 2023 - 24 FOR I & II SEMESTERS (PG)
IN THE SCHOOLS OF
ARCHITECTURE & TECHNOLOGY

JULY 2023 AUGUST 2023 SEPTEMBER 2023

Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun

01 02 01 02 03 04 05 06 01 02 03
Odd Semester- Student Odd Semester- Esperanza
Registration Induction Registration end (fresher' s Week)
start Program-VSP, end
HYD & BLR end
National Nutrition
Week Start
03 04 05 06 07 08 09 07 08 09 10 11 12 13 Master Chef -
Odd Semester- Season 02
Commencement of
Classwork
04 05 06 07 08 09 10
10 11 12 13 14 15 16 14 15 16 17 18 19 20
Teachers Day Sri Krishna
Janmastami
(VSP)
National
Nutrition Week
End
ANIME Day

Odd Semester- Independence GMUN start GMUN end


CCOM meeting-I Day

11 12 13 14 15 16 17
17 18 19 20 21 22 23 21 22 23 24 25 26 27
Odd Semester-
CCOM meeting-
III
Engineer’s Day
Student Student
Induction Induction
Program -VSP Program-HYD &
Start BLR Start
Bonalu (HYD)
18 19 20 21 22 23 24
28 29 30 31
Vinayaka Inter-
Chavithi Departmental
Cultural
24 25 26 27 28 29 30 Odd Semester-
CCOM meeting-II
Onam Competition

Esperanza (fresher'
s Week) start 25 26 27 28 29 30
Odd Semester-
CCOM meeting-
31 IV

OCTOBER 2023 NOVEMBER 2023 DECEMBER 2023

Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun

01 01 02 03 04 05 01 02 03
Odd Semester- Odd
CCOM meeting- Semester-
VII Closure of
Classwork
Kannada
Rajyothsav (BLR) World AIDS Day
02 03 04 05 06 07 08
Odd Semester-
Mid Term
Feedback start
06 07 08 09 10 11 12 04 05 06 07 08 09 10
Tech Fest start Tech Fest end Deepavali Odd Semester-End
Mahatma Gandhi Term Feedback
Jayanthi end
Community Odd Semester-
Submission of
Service (Blood
Donation/ Health
Camp/ Eye
13 14 15 16 17 18 19 continuous
evaluation marks
Check Up Camp) Even Semester- Odd Semester- Even Semester-
Registration CCOM Registration end Odd Semester-
start meeting-VIII Commencement
of Examinations
09 10 11 12 13 14 15 Children’s Day
Celebration of
International
Students' Day
Odd Semester-
Mid Term
Feedback end
World Mental
Health Day
GUSAC Carnival GUSAC Carnival
(VSP)/ Pramana (VSP)/ Pramana
Techno-Cultural Techno-Cultural
11 12 13 14 15 16 17
Odd Semester-
Fest (HYD)/ Fest (HYD)/
Prerna Techno- Prerna Techno- 20 21 22 23 24 25 26 Odd Semester-
Closure of
Examinations
Even Semester-
Commencement
of Classwork
CCOM meeting-V Cultural Fest Cultural Fest
(BLR) start (BLR) end Even Semester-
Add/Drop period
Batukamma start
(HYD)

27 28 29 30 18 19 20 21 22 23 24
16 17 18 19 20 21 22 Odd Semester-
End Term Even Semester- TEDx/ Christmas
Odd Semester- Feedback start Add/Drop period Workshop/ Celebration
CCOM meeting- end Seminar
VI Odd Semester-
CCOM meeting- Even Semester-
Navaratri & IX CCOM meeting-I
Dandiya
Celebration
25 26 27 28 29 30 31
23 24 25 26 27 28 29 Christmas Last date for
payment of tuition
fee for Even
Vijayadasami
Semester without
fine

30 31
Halloween Day/
Talent Hunt

JANUARY 2024 FEBRUARY 2024 MARCH 2024

Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun

01 02 03 04 05 06 07 01 02 03 04 01 02 03
Even Semester- Shore National Shore National SPICMACAY World Cancer
CCOM Annual Fest Annual Fest Day
meeting-II (VSP) start (VSP) end

08 09 10 11 12 13 14 05 06 07 08 09 10 11 04 05 06 07 08 09 10
Even Semester- Even Semester- Women’s Day
CCOM meeting- Mid Term
III Feedback start Kalakrithi Cultural
Night
Celebration of
National Youth
Day
12 13 14 15 16 17 18 11 12 13 14 15 16 17
Even Semester-
15 16 17 18 19 20 21
Mid Term Even Semester-
Feedback end CCOM
meeting-VII
Winter break Winter break Even Semester-
start end CCOM
meeting-V
Sankranti 18 19 20 21 22 23 24
22 23 24 25 26 27 28 19 20 21 22 23 24 25 Samyukta Fest
(International
Students)
Drama Drama
Republic Day Competition/ Competition/
Fine Arts Fine Arts
Competition
Cum Exhibition
start
Competition
Cum Exhibition
end
25 26 27 28 29 30 31
Holi Even Semester- Good Friday
29 30 31 26 27 28 29
CCOM
meeting-VIII
Even Semester-
CCOM Even Semester- National Science
meeting-IV CCOM Day
meeting-VI
Martyr’s Day

APRIL 2024 MAY 2024 JUNE 2024

Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun

01 02 03 04 05 06 07 01 02 03 04 05 01 02
Even Semester-End Thanks Giving World Health Summer Term - Summer Term -
Term Feedback Day/ Farewell Day Registration start Registration end
start Day
International
Labour Day

08 09 10 11 12 13 14 03 04 05 06 07 08 09
Even Semester- Even Semester-End
CCOM meeting- Term Feedback end
Ramzan (Eid-
Ul-Fitr)
Dr. B. R.
Ambedkar
06 07 08 09 10 11 12
IX Jayanthi Summer Term Basava Jayanthi
Ugadi start (BLR)

15 16 17 18 19 20 21 10 11 12 13 14 15 16
Even Semester- Even Semester- Sri Rama 13 14 15 16 17 18 19
Closure of Submission of Navami (VSP)
Classwork continuous
evaluation marks
Even Semester-
Commencement of 17 18 19 20 21 22 23
Examinations
20 21 22 23 24 25 26 Bakrid (Eid-Ul-
Zuha)
Odd Semester-
Registration
International
Yoga Day
start
22 23 24 25 26 27 28
ACE 2024/
Achiever's Day 24 25 26 27 28 29 30
27 28 29 30 31 Odd Semester-
Registration end
Summer Term
end

29 30
Even Semester-
Closure of
Examinations

JULY 2024

Mon Tue Wed Thu Fri Sat Sun

01 02 03 04 05 06 07
Odd Semester- Bonalu (HYD)
Commencement of
Classwork -
Academic Year
2024-25

08 09 10 11 12 13 14

15 16 17 18 19 20 21
Last date for
Payment of tuition
fee for ODD
semester without
fine

22 23 24 25 26 27 28

29 30 31

 DAYS OF ACADEMIC IMPORTANCE  WINTER BREAK  CAMPUS SPECIFIC HOLIDAYS  PUBLIC HOLIDAYS  STUDENT LIFE EVENTS AND ACTIVITIES
 OBSERVANCE OF SPECIAL DAYS

-By Registrar
JULY 2023 AUGUST 2023 SEPTEMBER 2023

01 Esperanza (fresher' s Week) end


02 Odd Semester-Registration start
01 National Nutrition Week Start
04 Student Induction Program-VSP, HYD & BLR end
01 Master Chef - Season 02
06 Odd Semester-Registration end
05 Teachers Day
07 Odd Semester-Commencement of Classwork
06 Sri Krishna Janmastami (VSP)
17 Student Induction Program -VSP Start 14 Odd Semester-CCOM meeting-I
07 National Nutrition Week End
17 Bonalu (HYD) 15 Independence Day
08 ANIME Day
19 Student Induction Program-HYD & BLR Start 18 GMUN start
11 Odd Semester-CCOM meeting-III
19 GMUN end
15 Engineer’s Day
28 Odd Semester-CCOM meeting-II
18 Vinayaka Chavithi
28 Esperanza (fresher' s Week) start
22 Inter-Departmental Cultural Competition
31 Onam
25 Odd Semester-CCOM meeting-IV

OCTOBER 2023 NOVEMBER 2023 DECEMBER 2023

02 Odd Semester-Mid Term Feedback start 01 Odd Semester-Closure of Classwork

02 Mahatma Gandhi Jayanthi 01 World AIDS Day


01 Odd Semester-CCOM meeting-VII
02 Community Service (Blood Donation/ Health Camp/ 04 Odd Semester-End Term Feedback end
01 Kannada Rajyothsav (BLR)
Eye Check Up Camp) 04 Odd Semester-Submission of continuous evaluation
09 Odd Semester-Mid Term Feedback end 06 Tech Fest start marks

09 Odd Semester-CCOM meeting-V 07 Tech Fest end 04 Odd Semester-Commencement of Examinations

10 World Mental Health Day 12 Deepavali 11 Odd Semester-Closure of Examinations

13 GUSAC Carnival (VSP)/ Pramana Techno-Cultural Fest 13 Even Semester-Registration start 12 Even Semester-Commencement of Classwork
(HYD)/ Prerna Techno-Cultural Fest (BLR) start 14 Odd Semester-CCOM meeting-VIII 12 Even Semester-Add/Drop period start
14 GUSAC Carnival (VSP)/ Pramana Techno-Cultural Fest 14 Children’s Day 19 Even Semester-Add/Drop period end
(HYD)/ Prerna Techno-Cultural Fest (BLR) end
17 Even Semester-Registration end 19 Even Semester-CCOM meeting-I
14 Batukamma (HYD)
17 Celebration of International Students' Day 22 TEDx/ Workshop/ Seminar
20 Odd Semester-CCOM meeting-VI
27 Odd Semester-End Term Feedback start 24 Christmas Celebration
20 Navaratri & Dandiya Celebration
27 Odd Semester-CCOM meeting-IX 25 Christmas
23 Vijayadasami
26 Last date for payment of tuition fee for Even Semester
31 Halloween Day/ Talent Hunt without fine

JANUARY 2024 FEBRUARY 2024 MARCH 2024

02 Even Semester-CCOM meeting-II


02 SPICMACAY
05 Shore National Annual Fest (VSP) start
04 World Cancer Day
07 Shore National Annual Fest (VSP) end 08 Women’s Day
06 Even Semester-Mid Term Feedback start
12 Even Semester-CCOM meeting-III 08 Kalakrithi Cultural Night
13 Even Semester-Mid Term Feedback end
12 Celebration of National Youth Day 12 Even Semester-CCOM meeting-VII
13 Even Semester-CCOM meeting-V
15 Winter break start 22 Samyukta Fest (International Students)
22 Drama Competition/ Fine Arts Competition Cum
15 Sankranti Exhibition start 25 Holi

19 Winter break end 23 Drama Competition/ Fine Arts Competition Cum 26 Even Semester-CCOM meeting-VIII
Exhibition end
26 Republic Day 29 Good Friday
27 Even Semester-CCOM meeting-VI
30 Even Semester-CCOM meeting-IV
28 National Science Day
30 Martyr’s Day

APRIL 2024 MAY 2024 JUNE 2024

02 Even Semester-End Term Feedback start


05 Thanks Giving Day/ Farewell Day

07 World Health Day


08 Even Semester-CCOM meeting-IX
09 Even Semester-End Term Feedback end
09 Ugadi 01 Summer Term - Registration start 17 Bakrid (Eid-Ul-Zuha)

11 Ramzan (Eid-Ul-Fitr) 01 International Labour Day 18 Odd Semester-Registration start

14 Dr. B. R. Ambedkar Jayanthi 03 Summer Term - Registration end 21 International Yoga Day

15 Even Semester-Closure of Classwork 06 Summer Term start 25 Odd Semester-Registration end

16 Even Semester-Submission of continuous evaluation 10 Basava Jayanthi (BLR) 28 Summer Term end
marks

16 Even Semester-Commencement of Examinations


17 Sri Rama Navami (VSP)

27 ACE 2024/ Achiever's Day


30 Even Semester-Closure of Examinations

JULY 2024

01 Odd Semester-Commencement of Classwork -


Academic Year 2024-25

07 Bonalu (HYD)
15 Last date for Payment of tuition fee for ODD semester
without fine

-By Registrar
Section :- T,I,M

08:00 to 12:00 13:00 to


WEEKDAY 09:00 to 09:50 10:00 to 10:50 11:00 to 11:50 14:00 to 14:50 15:00 to 15:50
08:50 to 13:50
CSEN1021_10188 CSEN1021_10188 12:50 CSEN1021_10188_ CSEN1021_10188_D_
Monday
_D_D324 _D_D324 D_D324 D324
CSEN1021_10188_ CSEN1021_10188_D_
Tuesday
D_D324 D324
Wednesda CSEN1021_10188_D_D32 CSEN1021_10188 CSEN1021_10188_ CSEN1021_10188_D_
y 4 _D_D324 D_D324 D324
CSEN1021_10188 CSEN1021_10188 CSEN1021_10188_ CSEN1021_10188_D_
Thursday
_D_D324 _D_D324 D_D204 D204
CSEN1021_10188 CSEN1021_10188 CSEN1021_10188_ CSEN1021_10188_D_
Friday
_D_D324 _D_D324 D_D324 D324
Saturday
16:00 to 17:00 to
16:50 17:50
Course name:

PROGRAMMING WITH PYTHON


(Course ID: CSEN1021 , Credits: 3, Semester : II )
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
i. Python – Numbers,
ii. Strings,
iii. Variables,
iv. operators,
v. expressions,
vi. statements,
vii. String operations,
viii. Math function calls,
ix. Input/output statements,
x. Conditional If,
xi. while and for loops.
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991.
It is used for:
❖ web development (server-side),
❖ software development,
❖ mathematics,
❖ system scripting.
Python Syntax compared to other programming languages:
Python was designed for readability, and has some similarities to the English language with influence from
mathematics.
Python uses new lines to complete a command/python statement, as opposed to other programming languages
which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes.
Other programming languages often use curly-brackets for this purpose.
Python Indentation
Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the
indentation in code is for readability only, the indentation in Python is very [Link] uses indentation to
indicate a block of code.
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
[Link] – Numbers,
There are three numeric types in Python: int , float , complex
Variables of numeric types are created when you assign a value to them:
Example:
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example:
print(type(x))
print(type(y))
print(type(z)
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
[Link] – Numbers,
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Example:
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
Note: You cannot convert complex numbers into another number type.
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
[Link] – Numbers,
Random Number
Python does not have a random() function to make a random number, but
Python has a built-in module called random that can be used to make random
numbers:
Example
Import the random module, and display a random number between 1 and 9:
import random
print([Link](1, 10))
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
[Link].
Strings in python are surrounded by either single quotation marks, or double quotation marks.
Assigning a string to a variable is done with the variable name followed by an equal sign and the
string:
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
[Link]
Variables are containers for storing data values.
Creating Variables:
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example:
x = 5, y = "John“
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Casting: If you want to specify the data type of a variable, this can be done with casting.
Example:
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
[Link]
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a = 4,A = "Sally“ #A will not overwrite a
Variable Names:
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
[Link]
Many Values to Multiple Variables:Python allows you to assign values to multiple variables in
one line:
Example : x, y, z = "Orange", "Banana", "Cherry“
Note: Make sure the number of variables matches the number of values, or else you will get an
error.
One Value to Multiple Variables: And you can assign the same value to multiple variables in
one line:
Example : x = y = z = "Orange“
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.
Example
Unpack a list: fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
Keywords in Python
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
[Link]
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
Arithmetic operators : +,-,*,/,%(modulus),//(floor division),**(exponentiaion))
Assignment operators: =
Comparison operators : = =, != , > , < , >= , <=
Logical operators : and , or , not)
Bitwise operators: Bitwise operators are used to compare (binary) numbers
& (AND) , | (OR) , ~ (NOT), ^ (XOR) ,
<< (zero fill left shift-Shift left by pushing zeros in from the right and let the
leftmost bits fall off) ,
>> ( Signed right shift - Shift right by pushing copies of the leftmost bit in
from the left, and let the rightmost bits fall off)
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
[Link]
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they
are actually the same object, with the same memory location:
Operator Description Exampl
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
[Link]
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in Returns True if a sequence with the
specified value is present in the object x in y
not in Returns True if a sequence with the specified
value is not present in the object x not in y
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
[Link],
An expression is a combination of operators and operands that is interpreted to
produce some other value. In any programming language, an expression is
evaluated as per the precedence of its operators. So that if there is more than
one operator in an expression, their precedence decides which operation will be
performed first
[Link],
i. A statement is an instruction that a Python interpreter can execute. So, in
simple words, we can say anything written in Python is a statement.
ii. Python statement ends with the token NEWLINE character. It means each
line in a Python script is a statement.
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
String functions(Built-in):
The upper() /lower() methods returns the string in upper/lower case

The strip() method removes any whitespace from the beginning or the end

The replace() [[Link](oldvalue, newvalue, count)]method replaces a string with


another string (count-Optional. A number specifying how many occurrences of the old value
you want to replace. Default is all occurrences )

The split() method returns a list where the text between the specified separator becomes the
list items.

The count() [[Link](value, start, end)] method returns the number of times a specified
value appears in the string
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
String functions(Built-in):
find()
The find()[ [Link](value, start, end)] method finds the first occurrence of the specified value. The
find() method returns -1 if the value is not found. The find() method is almost the same as the index()
method, the only difference is that the index() method raises an exception if the value is not foundThe
index() method finds the first occurrence of the specified value.

index()
The index() [[Link](value, start, end)]method raises an exception if the value is not found.
The index() method is almost the same as the find() method, the only difference is that the find()
method returns -1 if the value is not found. (See example below)

join()
The join() [[Link](iterable)] method takes all items in an iterable and joins them into one string.
A string must be specified as the separator.
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
String functions(Built-in):
The partition() [[Link](value)] method searches for a specified
string, and splits the string into a tuple containing three elements. The first
element contains the part before the specified string. The second element
contains the specified string. The third element contains the part after the
string.

The swapcase() [[Link]()]method returns a string where all the


upper case letters are lower case and vice versa

The endswith() [[Link](value, start, end)]method returns True if the


string ends with the specified value, otherwise False.

The startswith() [[Link](value, start, end)]method returns True if


the string starts with the specified value, otherwise False
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
Python Math
Built-in Math Functions
1. The min() and max() functions can be used to find the lowest or highest value in an iterable
2. The abs() function returns the absolute (positive) value of the specified number
3. The pow(x, y) function returns the value of x to the power of y (xy)
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
Python math Module( import math or import math as m)
Python has a built-in module that you can use for mathematical tasks. The math module has
a set of methods and constants.
[Link]() : Rounds a number up to the nearest integer
[Link]() : Returns the number of ways to choose k items from n items without repetition
and order
[Link]() : Returns the Euclidean distance between two points (p and q), where p and q are
the coordinates of that point
[Link]() : Returns E raised to the power of x
math.expm1(): Returns Ex - 1
[Link]() : Returns the absolute value of a number. Absolute denotes a non-negative
number. This removes the negative sign of the value if it has any
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
Python math Module
[Link]() : Returns the factorial of a number
[Link]() : Rounds a number down to the nearest integer
[Link]() : Returns the remainder of x/y
[Link]() : Returns the sum of all items in any iterable (tuples, arrays,
lists, etc.)
[Link]() : Returns the greatest common divisor of two integers
[Link]() : Rounds a square root number downwards to the
nearest integer
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
Python math Module
math.log10() : Returns the base-10 logarithm of x
math.log2() : Returns the base-2 logarithm of x
[Link]() : Returns the number of ways to choose k items from
n items with order and without repetition
[Link]() : Returns the value of x to the power of y
[Link]() : Returns the product of all the elements in an iterable
[Link]() : Returns the square root of a number
[Link]() : Returns the truncated integer parts of a number
CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
Python math Module
• Math Constants

• Constant Description

• math.e : Returns Euler's number (2.7182...)

• [Link] : Returns a floating-point positive infinity

• [Link] : Returns a floating-point NaN (Not a Number) value

• [Link] : Returns PI (3.1415...)

• [Link] : Returns tau (6.2831...)


CSEN1021 - PROGRAMMING WITH PYTHON
Module I: Introduction to Python
Control Statements
PYTHON CONTROL STATEMENTS
I. IF
II. IF_ELSE
III. NESTED IF_ELSE
IV. WHILE
V. FOR
“if” statement

if condition:
statement_1
statement_2
……
……
…….
statemnet_n
“if_else” statement

if condition:
statement_1
statement_2
…….
statemnet_n
else:
statement_1
statement_2
…….
statemnet_n
“if_elif_else(nested if_else)” statement
if condition:
statements
elif condition:
statements
elif condition:
statements
elif condition:
statements
else:
statements
“while” statement

while condition:
statement_1
statement_2
……
……
…….
statemnet_n
“for” statement

for iteration variable in definite condition:


statement_1
statement_2
……
……
…….
statemnet_n

Definite condition :
Ex: range of number s, list, dictionary, file…..etc
Course name:

PROGRAMMING WITH PYTHON


(Course ID: CSEN1021 , Credits: 3, Semester : II )
CSEN1021 - PROGRAMMING WITH PYTHON
Module II: Functions and Data Structures
Module II:
Functions
i. User defined Functions,
ii. parameters to functions,
iii. recursive functions.
Data structures
i. Lists,
ii. Tuples,
iii. Dictionaries,
iv. Strings.
[Link] structures.
I. STRINGS.
❖ . Besides numbers, Python can also manipulate strings, which can be expressed in
several ways.

❖ They can be enclosed in single quotes (‘…...') or double quotes (“…...") with the
same result.

❖ \ can be used to escape quotes.

❖ The string is enclosed in double quotes if the string contains a single quote and no
double quotes, otherwise it is enclosed in single quotes.

❖ String literals can span multiple lines. One way is using triple-quotes: """...""" or
'''...'''. End of lines are automatically included in the string, but it‟s possible to
prevent this by adding a \ at the end of the line

❖ Strings can be concatenated (glued together) with the + operator, and repeated with *.
[Link] structures.
I. STRINGS.
❖ Two or more string literals (i.e. the ones enclosed between quotes) next to each
other are automatically concatenated .This only works with two literals though,
not with variables or expressions. If you want to concatenate variables or a
variable and a literal, use +.

❖ Strings can be indexed (subscripted), with the first character having index 0.
Attempting to use an index that is too large will result in an error.

❖ Indices may also be negative numbers, to start counting from the right

❖ In addition to indexing, slicing is also supported. While indexing is used to


obtain individual characters, slicing allows you to obtain substring. out of
range slice indexes are handled gracefully when used for slicing.

❖ Python strings cannot be changed — they are immutable. Therefore, assigning to


an indexed position in the string results in an error
[Link] structures.
[Link]
Examples:
>>> 'spam eggs' # single quotes
'spam eggs‘

>>> 'doesn\'t' # use \' to escape the single quote...


"doesn't“

>>> "doesn't" # ...or use double quotes instead


"doesn't“

>>> '"Yes," he said.'


'"Yes," he said.‘

>>> "\"Yes,\" he said." '"Yes," he said.‘

>>> '"Isn\'t," she said.'


'"Isn\'t," she said.'
[Link] structures.
[Link]
Examples:
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a new line
First line.
Second line.

• If you don‟t want characters prefaced by \ to be interpreted as special characters, you can use
raw strings by adding an r before the first quote:
>>> print('C:\some\name') # here \n means newline!
C:\some ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
[Link] structures.
II. LISTS
Python knows a number of compound data types, used to group together other
values. The most versatile is the list, which can be written as a list of
comma-separated values (items) between square brackets. Lists might contain
items of different types, but usually the items all have the same type.

Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to
change their content

Like strings (and all other built-in sequence type), lists can be indexed and
sliced. Assignment to slices is also possible, and this can even change the size of
the list or clear it entirely
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g‘]

Lists also support operations like concatenation


[Link] Structures
II. LISTS

The list data type has some more methods. Here are all of the methods of list objects:

[Link](x) : Add an item to the end of the list. Equivalent to a[len(a):] = [x].

[Link](iterable) :Extend the list by appending all the items from the iterable.
Equivalent to a[len(a):] = iterable.

[Link](i, x) : Insert an item at a given position. The first argument is the index of the
element before which to insert, so [Link](0, x) inserts at the front of the list, and
[Link](len(a), x) is equivalent to [Link](x).

[Link](x) : Remove the first item from the list whose value is equal to x. It raises a
ValueError if there is no such item.
[Link] Structures
II. LISTS
[Link]([i ]) : Remove the item at the given position in the list, and return it. If no
index is specified, [Link]() removes and returns the last item in the list. (The square
brackets around the i in the method signature denote that the parameter is
optional, not that you should type square brackets at that position. )

[Link]() : Remove all items from the list. Equivalent to del a[:].

[Link](x[, start[, end ]]) : Return zero-based index in the list of the first item
whose value is equal to x. Raises a ValueError if there is no such item. The optional
arguments start and end are interpreted as in the slice notation and are used to
limit the search to a particular subsequence of the list. The returned index is
computed relative to the beginning of the full sequence rather than the start
argument
[Link] Structures
II. LISTS

[Link](x) : Return the number of times x appears in the list.

[Link](key=None, reverse=False) : Sort the items of the list in place (the arguments
can be used for sort customization, )

[Link]() : Reverse the elements of the list in place.

[Link]() : Return a shallow copy of the list. Equivalent to a[:].

Using Lists as Stacks

The list methods make it very easy to use a list as a stack, where the last element
added is the first element retrieved (“last-in, first-out”). To add an item to the top of
the stack, use append(). To retrieve an item from the top of the stack, use pop()
without an explicit index.
[Link] Structures
II. LISTS

Using Lists as Queues


It is also possible to use a list as a queue, where the first element added is the first
element retrieved (“first-in, first-out”); however, lists are not efficient for this
purpose. While appends and pops from the end of list are fast, doing inserts or pops
from the beginning of a list is slow (because all of the other elements have to be
shifted by one).

To implement a queue, use [Link] which was designed to have fast


appends and pops from both ends

>>> from collections import deque


>>> queue = deque(["Eric", "John", "Michael"])
>>> [Link]("Terry") # Terry arrives
>>> [Link]("Graham") # Graham arrives
>>> [Link]() # The first to arrive now leaves
'Eric'
>>> [Link]() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
[Link] Structures
III. Tuples

Similar to lists, tuples are sequences of arbitrary items. Unlike lists, tuples are
immutable, meaning you can't add, delete, or change items after the tuple is defined.
So, a tuple is similar to a constant list.

Create a Tuple by Using ()

>>> marx_tuple = ('Groucho', 'Chico', 'Harpo')


>>> marx_tuple
('Groucho', 'Chico', 'Harpo')

The tuple() conversion function makes tuples from other things:

>>> marx_list = ['Groucho', 'Chico', 'Harpo']


>>> tuple(marx_list)
('Groucho', 'Chico', 'Harpo')
[Link] Structures
III. Tuples

Tuples versus Lists

You can often use tuples in place of lists, but they have many fewer functions—
there is no append(), insert(), and so on—because they can‟t be modified after
creation.

Why not just use lists instead of tuples everywhere? Tuples use less space.

You can‟t clobber tuple items by mistake.

You can use tuples as dictionary keys

Function arguments are passed as tuples


[Link] Structures
IV. dictionaries

A dictionary is similar to a list, but the order of items doesn‟t matter, and they
aren‟t selected by an offset such as 0 or 1.

Instead, you specify a unique key to associate with each value.

This key is often a string, but it can actually be any of Python‟s immutable types:
boolean, integer, float, tuple, string, and others.

Create with {}

To create a dictionary, you place curly brackets ({}) around comma-separated key :
value pairs.

The simplest dictionary is an empty one, containing no keys or values at all.

>>> empty_dict = {}
>>> empty_dict
{}
[Link] Structures

IV. Dictionaries
Add or Change an Item by [ key ]
>>> pythons
{'Cleese': 'John', 'Jones': 'Terry', 'Palin': 'Michael',
'Chapman': 'Graham', 'Idle': 'Eric'}
>>> pythons['Gilliam'] = 'Gerry‘

Delete an Item by Key with del


>>> del pythons['Marx']

Delete All Items by Using clear()


>>> [Link]()
>>> pythons
{}
Test for a Key by Using in
>>> 'Chapman' in pythons True

Get an Item by [ key ]


>>> pythons['Cleese']
1. Data Structures
[Link]
Python also includes a data type for sets. A set is an unordered collection with no duplicate
elements.

Basic uses include membership testing and eliminating duplicate entries. Set objects also support
mathematical operations like union, intersection, difference, and symmetric difference.

A set is like a dictionary with its values thrown away, leaving only the keys. As with a dictionary,
each key must be unique.

You use a set when you only want to know that something exists, and nothing else about it. Use a
dictionary if you want to attach some information to the key as a value.

Create with set()


>>> empty_set = set()
>>> empty_set
Set()

>>> even_numbers = {0, 2, 4, 6, 8}


>>> even_numbers
{0, 8, 2, 4, 6}
1. Data Structures
[Link]

You can check whether one set is a subset of another (all members of the first set are also in the
second set) by using <= or issubset():

>>> a <= b
False
>>> [Link](b)
False

A superset is the opposite of a subset (all members of the second set are also members of the first).
This uses >= or issuperset():

>>> a >= b
False
>>> [Link](b)
False
5. FUNCTIONS
• The first step to code reuse is the function: a named piece
of code, separate from all others. A function can take any
number and type of input parameters and return any
number and type of output results.
• You can do two things with a function:
• Define it & Call it

• To define a Python function, you type def, the function


name, parentheses enclosing any input parameters to the
function, and then finally, a colon (:).

• Function names have the same rules as variable names


(they must start with a letter or _ and contain only letters,
numbers, or _).
5. FUNCTIONS
To define a Python function, you type def, the function
name, parentheses enclosing any input parameters to the
function, and then finally, a colon (:).
Syntax:
def function_name(arg1, arg2,.arg3, ....... , argN):
statement_1
statement_2
........................
........................
........................
statement_3
return statement
5. FUNCTIONS
Example:
• We can create a function that writes the Fibonacci series to an
arbitrary boundary:
>>> def fib(n): # write Fibonacci series up to n
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... >>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Course name:

PROGRAMMING WITH PYTHON


(Course ID: CSEN1021 , Credits: 3, Semester : II )
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Module III: Files and Packages
File:
I. Python Read Files,
II. Python Write/create Files,
III. Python Delete Files.
Pandas :
I. Read/write from csv, excel, json files,
II. add/ drop columns/rows,
III. aggregations,
IV. applying functions
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
FILES: File handling is an important part of any web application. Python has several functions for
creating, reading, updating, and deleting files.
File Handling
The key function for working with files in Python is the open() function. The open() function takes two
parameters; filename, and mode.
Syntax: f = open(filename, mode)
f is file object
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Read files
read() :By default the read() method returns the whole text, but you can also specify how
many characters you want to return:
f = open("demofi[Link]", "r")
print([Link]()) (or)
f = open("demofi[Link]", "r")
print([Link](5))
readline() :You can return one line by using the readline() method
f = open("demofi[Link]", "r")
print([Link]())
By looping through the lines of the file, you can read the whole file, line by line:
f = open("demofi[Link]", "r")
for x in f:
print(x)
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Close Files
It is a good practice to always close the file when you are done with it.
Example
Close the file when you are finish with it:
f = open("demofi[Link]", "r")
print([Link]())
[Link]()
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Write to an Existing File : write()
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example :
f = open("demofi[Link]", "w")
[Link]("Woops! I have deleted the content!")
[Link]()
Example:
f = open("demofi[Link]", "a")
[Link]("Now the file has more content!")
[Link]()
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Delete a File
To delete a file, you must import the OS module, and run its [Link]() function:
Example
Remove the file "demofi[Link]":
import os
[Link]("demofi[Link]") Check if File exist:
To avoid getting an error, you might want to check if the file exists before you try to delete it:
Example
Check if file exists, then delete it:
import os
if [Link]("demofi[Link]"):
[Link]("demofi[Link]")
else:
print("The file does not exist")
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Delete Folder
To delete an entire folder, use the [Link]() method:
Example
Remove the folder "myfolder":
import os
[Link]("myfolder")
Note: You can only remove empty folders.
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Pandas Introduction
What is Pandas?
Pandas is a Python library used for working with data sets. It has functions for analyzing, cleaning,
exploring, and manipulating data. The name "Pandas" has a reference to both "Panel Data", and
"Python Data Analysis" and was created by Wes McKinney in 2008.

Why Use Pandas?


Pandas allows us to analyze big data and make conclusions based on statistical theories. Pandas can
clean messy data sets, and make them readable and relevant. Relevant data is very important in data
science.
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Pandas Introduction
What Can Pandas Do?
Pandas gives you answers about the data. Like:
Is there a correlation between two or more columns?
What is average value?
Max value?
Min value?
Pandas are also able to delete rows that are not relevant, or contains wrong values, like empty or
NULL values. This is called cleaning the data.

Where is the Pandas Codebase?


The source code for Pandas is located at this github repository [Link]
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
installation of Pandas(windows)
If you have Python and PIP (pip is the de facto and recommended package-management system written in
Python and is used to install and manage software packages) already installed on a system, then installation of
Pandas is very easy.
Install it using this command:
C:\Users\Your Name>pip install pandas
If this command fails, then use a python distribution that already has Pandas installed like, Anaconda, Spyder
etc.
Import Pandas
Once Pandas is installed, import it in your applications by adding the import keyword:
import pandas (or) import pandas as pd
Checking Pandas Version
The version string is stored under __version__ attribute.
Example
import pandas as pd
print(pd.__version__)
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Pandas Series
What is a Series?
A Pandas Series is like a column in a table. It is a one-dimensional array
holding data of any type and an associated array of data labels, called its
index.
Example
Create a simple Pandas Series from a list:
import pandas as pd
a = [1, 7, 2]
myvar = [Link](a)
print(myvar)
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Pandas Series
Labels
If nothing else is specified, the values are labeled with their index number.
First value has index 0, second value has index 1 etc. This label can be
used to access a specified value.
Example
Return the first value of the Series:
print(myvar[0])
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Pandas Series
With the index argument, you can name your own labels.
Example
Create you own labels:
import pandas as pd
a = [1, 7, 2]
myvar = [Link](a, index = ["x", "y", "z"])
print(myvar)
When you have created labels, you can access an item by referring to the
label.
Example
Return the value of "y":
print(myvar["y"])
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Pandas Series
Key/Value Objects as Series
You can also use a key/value object, like a dictionary, when creating a
Series.
Example
Create a simple Pandas Series from a dictionary:
import pandas as pd
calories = {"day1": 420, "day2": 380, "day3": 390}
myvar = [Link](calories)
print(myvar)
Note: The keys of the dictionary become the labels.
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
DataFrames
What is a DataFrame?
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a
table with rows and columns. Data sets in Pandas are usually multi-dimensional tables,
called DataFrames. Series is like a column, a DataFrame is the whole table.
Example
Create a DataFrame from two Series:
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
myvar = [Link](data)
print(myvar)
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Locate Row
The DataFrame is like a table with rows and columns.
Pandas use the loc attribute to return one or more specified
row(s)
Example
Return row 0:
#refer to the row index:
print([Link][0])
Return row 0 and 1:
#use a list of indexes:
print([Link][[0, 1]])
CSEN1021 - PROGRAMMING WITH PYTHON
Module III: Files and Packages
Named Indexes : With the index argument, you can name your own indexes
Example
Add a list of names to give each row a name:
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
df = [Link](data, index = ["day1", "day2", "day3"])
print(df)
Locate Named Indexes :Use the named index in the loc attribute to return the specified row(s).
Example
Return "day2":
#refer to the named index:
print([Link]["day2"])
• Isnull() and notnull() functions in pandas should be used to detect
missing data
• A critical Series feature for many applications is that it automatically
aligns differently indexed data in arithmetic operations.
• critical method on pandas objects is reindex(), which means to create
a new object with the data conformed to a new index
• obj2 = [Link](['a', 'b', 'c', 'd', 'e'])
• [Link](['a', 'b', 'c', 'd', 'e'], fill_value=0)
Course name:
PROGRAMMING WITH PYTHON
(Course ID: CSEN1021 , Credits: 3, Semester : II )
[Link]
SOURCE OF INFORMATION:
[Link]
[Link]
[Link]
[Link]
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Module IV: Operations in database with suitable libraries

SQLite3:

CRUD operations (Create, Read, Update, and Delete) to manage data stored in a
database.

Matplotlib :

Visualizing data with different plots, use of subplots.

User defined packages, define test cases.


CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
What is SQLite?([Link]
SQLite is an in-process library that implements a self-contained, serverless,
zero-configuration, transactional SQL database engine.
The code for SQLite is in the public domain and is thus free for use for any purpose,
commercial or private.
SQLite is the most widely deployed database(Every Android device,Every iPhone
and iOS device ,Every Mac,Every Windows10 machine,Every Firefox, Chrome, and
Safari web browser,Every instance of Skype,Every instance of iTunesEvery
Dropbox client,Every TurboTax and QuickBooks,PHP and Python,Most television
sets and set-top cable boxes,Most automotive multimedia systems,Countless
millions of other applications) in the world with more applications than we can
count, including several high-profile projects.
Dwayne Richard Hipp designed SQLite in the spring of 2000.
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Python SQLite3:
Python SQLite3 module is used to integrate the SQLite database with Python.
It is a standardized Python DBI API 2.0 and provides a straightforward and
simple-to-use interface for interacting with SQLite databases.
There is no need to install this module separately as it comes along with Python
after the 2.5x version.
SQL is a query language and is very popular in databases. SQLite is a “light”
version that works over syntax very much similar to SQL.
Python has a library to access SQLite databases, called sqlite3, intended for
working with this database
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
SQLite Data Type
SQLite Data Type is a quality that defines the type of data of any object.
SQLite is different from other database systems; it uses dynamic type system.
Storage Classes could be used to define the format that SQLite uses to store
data on disk. SQLite provides five primary data types which are mentioned
below –
NULL – It is a NULL value.
INTEGER – It is an integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the
value.
REAL – It is a floating-point value, stored as an 8-byte floating number.
TEXT – It is a string, stored using the database encoding (UTF).
BLOB(Binary Large Object) – It is a group of data, stored exactly as it was
entered.
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Some important SQLite APIs:
connect():This API opens a connection to the SQLite database file.
cursor():This routine creates a cursor which will be used throughout the
database programming with Python
execute():This routine executes an SQLilte statements
commit():This method commits the current transaction
rollback(): This method rolls back any changes to the database since the last
call to commit().
close(): This method closes the database connection.
fetchall():This routine fetches all (remaining) rows of a query result, returning
a list. An empty list is returned when no rows are available.
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Importing SQLite3:
import sqlite3 or
import sqlite3 as sq
Database creation :
Step 1:
Connecting to the Database
Connecting to the SQLite Database can be established using the connect()
method, passing the name of the database to be accessed as a parameter. If that
database does not exist, then it’ll be created.
sqliteConnection = [Link]('[Link]’)
Ex: conctobj=[Link](“[Link]”)
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Step 2 :
To execute some queries a cursor has to be created using the cursor() method
on the connection instance, which will execute our SQL queries.
Syntax: cursor_object=connection_object.execute(“sql query”);
cursor = [Link]()
Ex: corsobj=[Link]()
Step 3:
The SQL query to be executed can be written in form of a string, and then
executed by calling the execute() method on the cursor object.
Step 4:
Then, the result can be fetched from the server by using the fetchall() method,
which in this case, is the SQLite Version Number.
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Python SQLite – Create Table:
In SQLite database we use the following syntax to create a table:
CREATE TABLE database_name.table_name(
column1 datatype PRIMARY KEY(one or more
columns),
column2 datatype,
column3 datatype,
…..
columnN datatype
);
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Python SQLite – Create Table:
import sqlite3 as sq
conobj=[Link]("[Link]")
cursobj=[Link]()
tb='''CREATE TABLE courseinfo(CNAME TEXT,CID TEXT,CREDITS
INTEGER,DEPTID INTEGER);'''
[Link](tb)
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Python SQLite – INSERT INTO Table:
The SQL INSERT INTO statement of SQL is used to insert a new row in a
table. There are two ways of using the INSERT INTO statement for inserting
rows:
METHOD 1:
INSERT INTO table_name VALUES (value1, value2, value3,…);
table_name: name of the table.
value1, value2,.. : value of first column, second column,… for the new record
METHOD 2:
INSERT INTO table_name (column1, column2, column3,..) VALUES ( value1,
value2, value3,..);
d
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Python SQLite – INSERT INTO Table:
row1="""INSERT INTO courseinfo VALUES("PyPro","CSEN1021",4,5);"""
row2="""INSERT INTO courseinfo VALUES("Phy","CSEN1021",3,10);"""
row3="""INSERT INTO courseinfo VALUES(“Chem","CSEN1021",3,11);"""
row4="""INSERT INTO courseinfo VALUES(“Maths","CSEN1021",4,12);"""
row5="""INSERT INTO courseinfo VALUES(“Wshp","CSEN1021",3,15);"""
[Link](row1)
[Link](row2)
[Link](row3)
[Link](row4)
[Link](row5)
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Python SQLite – Select Data from Table:
In SQLite the syntax of Select Statement is:
SELECT * FROM table_name;
* : means all the column from the table
To select specific column replace * with the column name or column names.
q="""SELECT * FROM courseinfo;""“
rtr=[Link](q)
for rw in rtr:
print(rw)
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Python SQLite – Select Data from Table:
>>>lr2=[Link](q).fetchall()
>>>lr2
[('PyPro', 'CSEN1021', 4, 5), ('PyPro', 'CSEN1021', 4, 5), ('PyPro',
'CSEN1021', 4, 5), ('PyPro', 'CSEN1021', 4, 5), ('PyPro', 'CSEN1021', 4, 5),
('PyPro', 'CSEN1021', 4, 5)]
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Python SQLite – Queries:
Where clause is used in order to make our search results more specific, using the
where clause in SQL/SQLite we can go ahead and specify specific conditions that have
to be met when retrieving data from the database.
If we want to retrieve, update or delete a particular set of data we can use the where
clause. If we don’t have condition matching values in your database tables we
probably didn’t get anything returned.
WHERE Clause in SQL:
Syntax:
SELECT column_1, column_2,…,column_N
FROM table_name
WHERE [search_condition]
Here, in this [search_condition] you can use comparison or logical operators to specify
conditions.
For example: = , > , < , != , LIKE, NOT, etc.
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Python SQLite – Queries:
DELETE statement:
In SQLite database we use the following syntax to delete data from a table:
DELETE FROM table_name [WHERE Clause]

DROP statement:
DROP is used to delete the entire database or a table. It deleted both records in
the table along with the table structure.
Syntax: DROP TABLE TABLE_NAME;
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Python SQLite – Queries:
UPDATE statement:
The UPDATE statement in SQL is used to update the data of an existing table
in the database. We can update single columns as well as multiple columns
using UPDATE statement as per our requirement.

Syntax:
UPDATE table_name SET column1 = value1, column2 = value2,…
WHERE condition;
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
What is Matplotlib?
I. Matplotlib is a low-level graph plotting library in python that serves as a
visualization utility.
II. Matplotlib was created by John D. Hunter.
III. Matplotlib is open source and we can use it freely.
IV. Matplotlib is mostly written in python, a few segments are written in C,
Objective-C and Javascript for Platform compatibility.
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of
Matplotlib is very easy.
Install it using this command(On windows):
C:\>pip install matplotlib
Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding the
import module statement:
import matplotlib
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries

Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported
under the plt alias:
import [Link] as plt
Example:
import [Link] as plt
import numpy as np
xpoints = [Link]([0, 6])
ypoints = [Link]([0, 250])
[Link](xpoints, ypoints)
[Link]()
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Plotting x and y points
• The plot() function is used to draw points (markers) in a diagram.
• By default, the plot() function draws a line from point to point.
• The function takes parameters for specifying points in the
diagram.
• Parameter 1 is an array containing the points on the x-axis.
• Parameter 2 is an array containing the points on the y-axis.
• If we need to plot a line from (1, 3) to (8, 10), we have to pass two
arrays [1, 8] and [3, 10] to the plot function.
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Markers
You can use the keyword argument marker to emphasize each point with a specified
marker:
[Link]([6,3,8,-6,9,10], marker = 'o’)
Example:
Marker Description
‘o’ Circle
'*’ Star
'.’ Point
',’ PixelMarker Size
You can use the keyword argument markersize or the shorter version, ms to set the size
of the markers
[Link](([6,3,8,-6,9,10], marker = 'o', ms = 20)
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Markers
You can use the keyword argument markeredgecolor or the shorter mec to set the
color of the edge of the markers
You can use the keyword argument markerfacecolor or the shorter mfc to set the
color inside the edge of the marker
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
The line value can be one of the following:
Line Syntax Description
'-’ Solid line
':’ Dotted line
'--’ Dashed line
'-.’ Dashed/dotted line
The short color value can be one of the following:
Color Reference
Color Syntax Description
'r’ Red
'g’ Green
'b’ Blue
'c’ Cyan
'm’ Magenta
'y’ Yellow
'k’ Black
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Format Strings fmt
You can use also use the shortcut string notation parameter to specify the marker.
This parameter is also called fmt, and is written with this syntax:
marker|line|color
Ex:
[Link]([1,2,3,4,5,6,7,8,9],[1,9,2,8,3,7,4,6,5],'*-r',ms=20,mec='r',mfc='b’)
[Link]([1,2,3,4,5,6,7,8,9],[1,9,2,8,3,7,4,6,5],'*:r',ms=20,mec='r',mfc='b')
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Hexadecimal Colors
Hexadecimal color values are also supported in all browsers.
A hexadecimal color is specified with: #RRGGBB.
RR (red), GG (green) and BB (blue) are hexadecimal integers between 00 and FF
specifying the intensity of the color.
For example, #0000FF is displayed as blue, because the blue component is set to its
highest value (FF) and the others are set to 00.
[Link]([1,2,3,4,5,6,7,8,9],[1,9,2,8,3,7,4,6,5],'*:r',ms=20,mec='#000000',mfc
='#ffffff’)
[Link]([1,2,3,4,5,6,7,8,9],[1,9,2,8,3,7,4,6,5],'*:r',ms=20,mec='#10aaff',mfc='
#ffaabb')
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Hexadecimal Colors
#000000-Black #000080-Navy #00008B-DarkBlue#0000CD-MediumBlue
#0000FF-Blue #006400-DarkGreen #008000-Green#008080-Teal
#008B8B-DarkCyan

[Link]([1,2,3,4,5,6,7,8,9],[1,9,2,8,3,7,4,6,5],'*:r',ms=20,mec='Navy',mfc='DarkBlue’)
[Link]([1,2,3,4,5,6,7,8,9],[1,9,2,8,3,7,4,6,5],'*:r',ms=20,mec='cyan',mfc='gray')
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries

Line styles:
You can use the keyword argument line style, or shorter ls, to change the style of the
plotted line
Line styles : 'solid' (default) ‘-’, 'dotted' ‘:’ ,'dashed' '--’ , 'dashdot’ ‘-.'
'None’
Line Color: You can use the keyword argument color or the shorter c to set the color of
the line.
Linewidth: You can use the keyword argument linewidth or the shorter lw to change
the width of the line.

[Link]([1,2,3,4,5,6,7,8,9],[1,9,2,8,3,7,4,6,5],ls='dotted',c='green',lw='10',ms=20,m
ec='cyan',mfc='gray')
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Create Labels for a Plot
With Pyplot, you can use the xlabel() and ylabel() functions to set a label for the x- and
y-axis.
Create a Title for a Plot
With Pyplot, you can use the title() function to set a title for the plot
Position the Title
You can use the loc parameter in title() to position the title.
Legal values are: 'left', 'right', and 'center'. Default value is 'center'
Set Font Properties for Title and Labels
You can use the fontdict parameter in xlabel(), ylabel(), and title() to set font properties
for the title and labels.
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
font1 = {'family':'serif','color':'blue','size':20}
font2 = {'family':'serif','color':'darkred','size':15}

[Link]("Sports Watch Data", fontdict = font1,loc=‘left’)


[Link]("Average Pulse", fontdict = font2)
[Link]("Calorie Burnage", fontdict = font2)
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Add Grid Lines to a Plot
With Pyplot, you can use the grid() function to add grid lines to the plot
Specify Which Grid Lines to Display
You can use the axis parameter in the grid() function to specify which grid lines to
display.
Legal values are: 'x', 'y', and 'both'. Default value is 'both’.
Set Line Properties for the Grid
You can also set the line properties of the grid, like this:
grid(color = 'color', linestyle = 'linestyle', linewidth = number).

[Link](color = 'green', linestyle = '--', linewidth = 0.5)


CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Display Multiple Plots
With the subplot() function you can draw multiple plots in one figure
The subplot() Function
The subplot() function takes three arguments that describes the layout of the figure.
The layout is organized in rows and columns, which are represented by the first and
second argument.
The third argument represents the index of the current plot.
[Link](1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.
[Link](1, 2, 2)
#the figure has 1 row, 2 columns, and this plot is the second plot.
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Title
You can add a title to each plot with the title() function
Super Title
You can add a title to the entire figure with the suptitle() function
#plot 1: x = [0, 1, 2, 3] y = [3, 8, 1, 10]
[Link](1, 2, 1)
[Link](x,y)
[Link]("SALES")
#plot 2: x = [0, 1, 2, 3] y = [10, 20, 30, 40]
[Link](1, 2, 2)
[Link](x,y)
[Link]("INCOME")
[Link]("MY SHOP")
[Link]()
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Creating Scatter Plots
With Pyplot, you can use the scatter() function to draw a scatter plot.
The scatter() function plots one dot for each observation. It needs two arrays of the
same length, one for the values of the x-axis, and one for values on the y-axis
[Link](x, y)
Colors
You can set your own color for each scatter plot with the color or the c argument
Color Each Dot
You can even set a specific color for each dot by using an array of colors as value for the
c argument(Note: You cannot use the color argument for this, only the c argument.)
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
ColorMap
The Matplotlib module has a number of available colormaps.
A colormap is like a list of colors, where each color has a value that ranges from 0 to 100.
How to Use the ColorMap
You can specify the colormap with the keyword argument cmap with the value of the
colormap, in this case 'viridis' which is one of the built-in colormaps available in Matplotlib.
colors = [0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100]
[Link](x, y, c=colors, cmap='viridis’)
You can include the colormap in the drawing by including the [Link]() statement.
Size
You can change the size of the dots with the s argument
Alpha
You can adjust the transparency of the dots with the alpha argument.
Colorbar
You can include the colormap in the drawing by including the [Link]() statement
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
over1=[0,3,6,-1,0,0]
over2=[0,-1,6,-1,6,0]
over3=[2,4,1,0,0,-1]
Ball=[1,2,3,4,5,6]
clrs1=[65,65,66,99,65,65]
clrs2=[85,99,85,99,85,85]
clrs3=[45,45,45,45,45,99]
[Link](Ball,over1,c=clrs1,cmap='viridis',s=90)
[Link](Ball,over2,c=clrs2,cmap='viridis',s=70)
[Link](Ball,over3,c=clrs3,cmap='viridis',s=100)
[Link]()
[Link]()
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs.(the barh() function for
horizontal bars)
The bar() function takes arguments that describes the layout of the bars.
The categories and their values represented by the first and second argument as arrays
Bar Color
The bar() and barh() takes the keyword argument color to set the color of the bars
Bar Width
The bar() takes the keyword argument width( 0 to 1, default is 0.8) to set the width of
the bars(For horizontal bars, use height instead of width)
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
subject=["Cprog","Phy","Chem","Maths","[Link]","WorkShp"]
Passprcnt=[90,87,70,78,68,80]
[Link](subject,Passprcnt,color="green",width=0.65)
[Link]("Name of the subject")
[Link]("Pass %")
[Link]("Result Analysis of I Semester")
[Link]()
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Histogram
A histogram is a graph showing frequency distributions.
It is a graph showing the number of observations within each given interval.
Create Histogram
In Matplotlib, we use the hist() function to create histograms.
The hist() function will use an array of numbers to create a histogram, the array is sent
into the function as an argument.
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
cgpaCSE=[8.0,8,8.5,9,8.70,6,8,6.4,8.0,8,7.8,6.9,6,8.0,0,0,0,8.0,8,8.5,9,8.70,6,8,6.4,8.0,8,7.8,
6.9,6,8.0,0,0,0]
[Link](cgpaCSE)
[Link]("CGPA distribution")
[Link]("Frequency")
[Link]("CGPA Analysis")
[Link]()
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Creating Pie Charts
With Pyplot, you can use the pie() function to draw pie charts
By default, the plotting of the first wedge starts from the x-axis and move
counterclockwise
Labels
Add labels to the pie chart with the label parameter.
The label parameter must be an array with one label for each wedge
Start Angle
The startangle parameter is defined with an angle in degrees, default angle is 0.
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Explode
Maybe you want one of the wedges to stand out? The explode parameter allows you to
do that.
The explode parameter, if specified, and not None, must be an array with one value for
each wedge. Each value represents how far from the center each wedge is displayed.
myexplode = [0.2, 0, 0, 0]
Shadow
Add a shadow to the pie chart by setting the shadows parameter to True
Colors
You can set the color of each wedge with the colors parameter.
The colors parameter, if specified, must be an array with one value for each wedge
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
Legend
To add a list of explanation for each wedge, use the legend() function
Legend With Header
To add a header to the legend, add the title parameter to the legend function
CSEN1021 - PROGRAMMING WITH PYTHON
Module IV: Operations in database with suitable libraries
AmountinRs=[5000,1000,0,20000,3000]
SpendingON=["Food","Books","FinalExamFee","GFrndORByFRND","Charity"]
[Link](AmountinRs,labels=SpendingON,explode=myexp)
[Link](title="Spending details of MAY_2022")
[Link]()
1. program to read the first n lines of a file.
For example:

Tes Input Result


t

1 [Link].t banan
xt a
3
apple

grape
s

2. program to append text to a file and display the text.


For example:

Tes Input Result


t

1 [Link] banana
t apple
watermelo grapes
n papaya
[Link] pomogranate
t orange
mosambi
blue berry
dragon
fruit

pinapple
mango
watermelon

3. to count the number of words, characters, and lines from a text file [Link]
4. Write a Python program to count the frequency of words available in a given text file.
5. Write a python program to count number of words and lines in given file.
File name :FILE_1.txt\
6. write a Python program to display the longest word/words from a given text file.
Input File: FILE_5.txt
7. Write a Python program to print the total number of names(lines) and the count of
names starting with 'B', 'C', or 'D'.

8. Write Python code to change the data from a file [Link] into uppercase, save the
result in file [Link] and display the contents of file2

For example:

Tes Input Result


t

1 ("Hello", "World") ("HELLO", "WORLD")


[Good Morning] [GOOD MORNING]
(Welcome to Python (WELCOME TO PYTHON CLASS)
Class) COMPLETE THE ASSIGNMENT
"DUE DATE FOR SUBMISSION IS
TOMORROW"

9. Write a python code to reverse the contents of input file([Link]) and store it in
another file and display its contents

10. From a given file [Link], join the strings of each line of a file and write the result into
another file [Link], also display the contents of f1.

For example:

Tes Input Result


t

1 good morning goodmorning


welcome to welcometocla
class ss

11. Write a Pandas program to convert a dictionary to a Pandas series.


For example:
Tes Input Result
t

2 {101: 'Smith', 102: 'John', 101 Smith


103:'Peter'} 102 John
103 Peter
dtype:
object

12. Given an input file([Link]), find the longest word in the file.
For example:

Tes Input Result


t

1 Machine Learning ['Programming


Neural Networks ']
Python
Programming

13. Write a program to count the number of upper-case alphabets present in a text file
“[Link]”
For example:

Tes Input Result


t

1 Welcome Total no. of uppercase alphabets :


Hello World 11
Python Programming
Ease of programs
Predefined methods
Less lines of code
Has Many built in
packages
Popular now a days

14. Write a program to display all the lines in a file “[Link]” along with line/record
number.
15. Write a Python program to read the content of a given text file and display the reverse of
the content.
16. A file is containing ONLY registration numbers of students i.e one registration number
in each line. Read the each registration number ,split it and write it back in the same file. So,
file should contain ONLY split data.
File name: FILE_4.txt
Example : line 1: HU22CSEN0600345 split it as--> HU#22#CSEN#06#00345
and write it back.
17. Write a python program to count number of words having # symbol at the beginning or
at the ending or at the beginning and ending in given file.
File name: FILE_2.txt
Example words : #hello
hello#
#hello#
18. Write a python program to count number of words NOT having # symbol at the
beginning or at the ending or at the beginning and ending in given file.
File name: FILE_3.txt
19. Write a Python program to find the third largest number from a given list of [Link]
the Python set data type
For example:

Test Result

print(third_largest([1, 2, 3, 4, 5, 6, 7, 8, 9])) 7

print(third_largest([1, 2, 3, 4, 5, 5, 6, 7, 7, 8, 8, 9, 8
10]))

print(third_largest([1, 2, 3])) 1

20. Write a Python program to Check if two lists have at least one element common in them
or not
For example:

Test Result
print(common_data([1, 2, 3, 4, 5], [5, 6, 7, 8, True
9]))

print(common_data([1, 2, 3, 4, 5], [6, 7, 8, False


9]))

21. Write a Python script to print a dictionary where the keys are numbers between 1 and N
(both included) and the values are square of keys.
For example:

T Inp Result
e ut
st

1 16 {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100,


11: 121, 12: 144, 13: 169, 14: 196, 15: 225}

2 5 {1: 1, 2: 4, 3: 9, 4: 16}

22. Write a Python program that finds all pairs of elements in a list whose sum is equal to a given value.

For example:

Test Result

find([5, 2, 3, 4, 1, 6, 7], 7, 5 2
7) 3 4
1 6

find([1, 2, 3, 4, 5, 6], 6, 5) 1 4
2 3

23. Write python program to read 2 strings and store them in 2 variables.
1) Display the length of the two strings
2)concatenate the two strings and print them
For example:
Tes Input Result
t

1 k 1
aravind 7
K aravind

2 A 1
jagadis 8
h A
jagadish

24. Write a Python program to find the list of words that are longer than n from a given list
of words.
For example:

Test Result

print(long_words(3, "The quick brown fox jumps ['quick', 'brown', 'jumps',


over the lazy dog")) 'over', 'lazy']

print(long_words(5, "The following are the ['following', 'longest']


longest words from a text file"))

25. Write python code to merge two dictionaries into a single one.
For example:

Te Input Result
st

1 {'x': 10, 'y': 8} {'x': 10, 'y': 8, 'a': 6, 'b': 4}


{'a': 6, 'b': 4}

2 {'color': 'Red', 'Book': {'color': 'Red', 'Book': 'C', 'Clothes':


'C'} 'Jeans', 'Movie': 'Matrix'}
{'Clothes': 'Jeans',
'Movie': 'Matrix'}
26. Write a Python program to calculate the product, multiplying all the numbers in a given
tuple.
For example:

Input Result

(4, 3, 2, 2, -1, -864


18)

(2, 4, 8, 8, 3, 2, 27648
9)

27. Write a Python program to remove duplicates from a list.


For example:

Input Result

[10,20,30,20,10,50,60,40,80,50, [10, 20, 30, 50, 60, 40,


40] 80]

[1,2,3,2,1,50,60] [1, 2, 3, 50, 60]

[-25,-37,-20,-25,-3,-7,-25] [-25, -37, -20, -3, -7]

28. write a python function program to find the second smallest number in a list.
For example:

Input Result

[1, 1, 3, 5, 1
7]

[1, 3, 5, 7] 3

[Link] a Pandas program to select the rows where the number of attempts in the
examination is greater than 2.
For example:
T Input Result
e
s
t

1 exam_data = {'name':
['Anastasia','Dima','Katherine','James','Emily','Michael','Matthew', name
'Laura', 'Kevin', 'Jonas'],'score': [12.5, 9, 16.5, [Link], 9, score
20,14.5, [Link], 8, 19],'attempts' : [1, 3, 2, 3, 2, 3, 1, 1, 2, attemp
1],'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', ts
'no', 'yes']} qualif
y
1
Dima
9.0
3
no
3
James
NaN
3
no
5
Michae
l
20.0
3
yes

30 Write a Pandas program to add, subtract, multiple, and divide two Pandas Series.
take the following two series objects as input
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
31. Write a Pandas program to count the number of rows and columns of a DataFrame

[Link] the given csv file and answer the following questions
File name:
C_PROGRAMMING_SET_1.csv

Display emails of students who scored marks 0 ( zero) marks in CASE_STUDY


33. Read the csv file and answer the following question
File name :C_PROGRAMMING_SET_1.csv
Display all quiz marks of the following pin numbers.
HU22CSEN010093
7

HU22CSEN010192
6

HU22CSEN040014
8

HU22CSEN040018
3

HU22CSEN050026
0

34. Read the csv file and answer the following question
FIle name:
C_PROGRAMMING_SET_1.csv

How many students did not submit coursera certificate, Display their names and
registration numbers.
35. Read the csv file and answer the following question
File Name:
C_PROGRAMMING_SET_1.csv

In which quiz and mid exam many students where absent .


Note: You can assume value "NaN "as absent

Answer:(penalty regime: 0 %)
36. Read the given csv file and answer the following questions
File name:
C_PROGRAMMING_SET_1.csv

Display Registration number of students who scored marks in between


8,10 (both inclusive ) in MID_1 examination

37. Write a Pandas program from given dictionary exam_data to get the first 3 rows of
DataFrame.
Sample DataFrame:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
38. Write a Pandas program to replace all the NaN values with Zero's in a column of a
dataframe.
Original DataFrame:

Sample data:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0
2 2 Katherine yes 16.5
3 3 James no NaN
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no NaN
8 2 Kevin no 8.0
9 1 Jonas yes 19.0
New DataFrame replacing all NaN with 0:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0
2 2 Katherine yes 16.5
3 3 James no 0.0
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no 0.0
2 Kevin no 8.0
9 1 Jonas yes 19.0

39. Write a Pandas program to drop a 2nd and 4th rows from a specified DataFrame.

Original DataFrame

col1 col2 col3

0147

1458

2369

3470

4581
40 . Read the given "csv" file and answer the following question.
File name: C_PROGRAMMING_SET_1.csv
Display names top 3 of students who scored highest marks in MID_1 exam

MID2 Questions( Strings, Dictionaries from module 2 and all topics of Module3)

Please paste questions according to the category

Easy(total 15)
1. You are given two synonym dictionary file parse through each file line by line and
retrieve the data each line will be a word with its synonyms in this format

responsibility - authority, control, leadership


your task is to form a dictionary which looks like the below one
d = {"responsibility" : ["authority", "control", "leadership"]}
Hint:
9Read the file line by line as strings into a list lst
Replace space and '-' ' -' with ',' and '\n' with nothing ''
Take the ith string from the list lst and split them as templst
make the0th them of templst as key and remaining as list of values
[Link] the 4th step by going through the other terms of templst and appending them into
the dictionary key
Repeate the steps 3 and 5 until the len of lst

2.
# to write a list to a file [Link] and display the contents of file4
l=[1,20.5,['abc',4],"hello"]
f = open("[Link]","w")
[Link](str(l))
f = open("[Link]","r")
print([Link]())

input:

output:
[1,20.5,['abc',4],"hello"]

3.
# to write a dictionary to a file and display the contents of a file
d={1:"one", 2:"two", 3:"three",'a':['abc', 'bcd']}
f = open("[Link]","w")
for i in [Link]():
[Link](str(i))
f = open("[Link]","r")
print([Link]())
input:
{1:"one", 2:"two", 3:"three",'a':['abc', 'bcd']}
output:
(1, 'one')(2, 'two')(3, 'three')('a', ['abc', 'bcd'])

4.
#### to read n lines from a file [Link]
fp = open("[Link]","r")
n=int(input())
for j in range(n):
print([Link]().strip("\n"))

input:
3
[Link] contents:
("Hello", "World")
[Good Morning]
(Welcome to Python Class)
Complete the assignment
“Due date for submission is tomorrow”
output:
("Hello", "World")
[Good Morning]
(Welcome to Python Class)

5.
### to merge two dictionaries into a single one
s1=input()
s2=input()
dict1=eval(s1)
dict2=eval(s2)
[Link](dict2)
print(dict1)

input:
{'x': 10, 'y': 8}
{'a': 6, 'b': 4}

Output:
{'x': 10, 'y': 8, 'a': 6, 'b': 4}

6. Write a Pandas program to convert a Panda module Series to Python list


and it’s type.
Sample Solution:
import pandas as pd
ds = [Link]([2, 4, 6, 8, 10])
print("Pandas Series and type")
print(ds)
print(type(ds))
print("Convert Pandas Series to Python list")
print([Link]())
print(type([Link]()))

Pandas Series and type


0 2
1 4
2 6
3 8
4 10
dtype: int64

Convert Pandas Series to Python list


[2, 4, 6, 8, 10]
7. Write a Pandas program to create and display a DataFrame from a
specified dictionary data which has the index labels.

Sample Python dictionary data and list labels:


exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily',
'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no',
'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Expected Output:
name score attempts qualify
a Anastasia 12.5 1 yes
b Dima 9.0 3 no
c Katherine 16.5 2 yes
d James NaN 3 no
e Emily 9.0 2 no
f Michael 20.0 3 yes
g Matthew 14.5 1 yes
h Laura NaN 1 no
i Kevin 8.0 2 no
j Jonas 19.0 1 yes

8. Write a Python script to add a key to a dictionary.


Sample Solution:
d = {0:10, 1:20}
print(d)
[Link]({2:30})
print(d)

Expected output:
{0: 10, 1: 20}
{0: 10, 1: 20, 2: 30}
9. Write a Python script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are square of keys.
Sample Solution:
d=dict()
for x in range(1,16):
d[x]=x**2
print(d)

Expected output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11:
121, 12: 144, 13: 169, 14: 196, 15: 225}

10. Write a Python program to sum all the items in a dictionary.


Sample Solution:

my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))

Sample Output: 293

11. Write a Pandas program to convert a given list of lists into a


Dataframe.
Sample Solution:
import pandas as pd
my_lists = [['col1', 'col2'], [2, 4], [1, 3]]
# sets the headers as list
headers = my_lists.pop(0)
print("Original list of lists:")
print(my_lists)
df = [Link](my_lists, columns = headers)
print("New DataFrame")
print(df)

Expected output:
New DataFrame:
col1 col2
0 2 4
1 1 3

12. Accept five names from the user and write in a file “[Link]” and display them
f = open("[Link]","w")
for i in range(5):
n = input()
[Link](n)
[Link]("\n")
[Link]()
f = open("[Link]","r")
print([Link]())

[Link] python code to merge two dictionaries into a single one.

s1=input()
s2=input()
dict1=eval(s1)
dict2=eval(s2)
[Link](dict2)
print(dict1)

14. Write a program in python to display number of lines in a file(“[Link]”).

f=open("[Link]","r")
l=[Link]()
print(len(l))

Moderate(total 15)

1. You will be given a text file like the below one


Visakhapatnam City
Tanali Town
Mumbai City
Kodavatikallu Village
Maavooru Village
Anantapuram Town
your task is to form a dictionary which looks like this

{'City':['Visakhapatnam', 'Mumbai'], 'Town':['Tanali', 'Anantapuram'], 'Village':['Kodavatikallu',


'Maavooru']}
Hint:

1. Read each line into a list lst as strings


2. Next split ith index string in list lst into a templst where you will visualize them as two
seperate strings as shown below
['Visakhapatnam', 'City']
[Link] the second term as key and first term as values
4. As key cannot be duplicated check if the key is already there or not. I there append the found
value or create a new key
Repeate the steps 2-4 until the len of list ls

2.
### to copy the contents of a file [Link] into [Link] and display
the contents of file2.
fp=open("[Link]", "r")
fp1=open("[Link]", "w")
for line in fp:
[Link](line)
[Link]()
[Link]()
fp1=open("[Link]", "r")
print([Link]())
[Link]()

input:
[Link] contents:
GOOD MORNING
COMPLETE THE ASSIGNMENT
DUE DATE FOR SUBMISSION IS TOMORROW

Output:
GOOD MORNING
COMPLETE THE ASSIGNMENT
DUE DATE FOR SUBMISSION IS TOMORROW

3.
### to change the data from a file [Link] into uppercase,
### save the result in file [Link]
### and display the contents of file2
fp=open("[Link]", "r")
fp1=open("[Link]", "w")
for line in fp:
l=[Link]("\n")
for i in l:
w=''.join(i)
[Link]([Link]())
[Link]('\n')
fp1=open("[Link]", "r")
print([Link]())
[Link]()

input:
("Hello", "World")
[Good Morning]
(Welcome to Python Class)

Output:
("HELLO", "WORLD")
[GOOD MORNING]
(WELCOME TO PYTHON CLASS)

4.
# from a given file [Link], join the strings of each line of a file and
# write the result into another file [Link], also display the contents
# of file2.
f=open("[Link]","r")
fp=open("[Link]","w")
for line in f:
l=[Link]("\n")
w=[Link]()
w="".join(w)
[Link](w)
[Link]("\n")
fp=open("[Link]","r")
print([Link]())

input:
[Link] contents:
good morning
welcome to class

output:
goodmorning
welcometoclass

5.
# to convert a string of key value pairs to a dictionary

# input a String
string = input()

# eval() convert string to dictionary


Dict = eval(string)
print(Dict)

input:
{'one':10, 'two':20, 'three':30}

Output:
{'one':10, 'two':20, 'three':30}

input:
{10:'one', 20:'two', 30:'three'}

Output:
{10:'one', 20:'two', 30:'three'}

6. Write a Pandas program to convert a dictionary to a Pandas series.


Sample dictionary: d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}

Sample Solution:
import pandas as pd
d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}
print("Original dictionary:")
print(d1)
new_series = [Link](d1)
print("Converted series:")
print(new_series)

Converted series:
a 100
b 200
c 300
d 400
e 800
dtype: int64

7. Write a Pandas program to get the first 3 rows of a given DataFrame.


Sample DataFrame:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Sample solution:
import pandas as pd
import numpy as np

exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',


'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

df = [Link](exam_data , index=labels)
print("First three rows of the data frame:")
print([Link][:3])

Expected output:
First three rows of the data frame:
name score attempts qualify
a Anastasia 12.5 1 yes
b Dima 9.0 3 no
c Katherine 16.5 2 yes

8. Write a Pandas program to replace all the NaN values with Zero's in a column of a
dataframe.

Original DataFrame:

Sample data:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0
2 2 Katherine yes 16.5
3 3 James no NaN
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no NaN
8 2 Kevin no 8.0
9 1 Jonas yes 19.0
New DataFrame replacing all NaN with 0:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0
2 2 Katherine yes 16.5
3 3 James no 0.0
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no 0.0
8 2 Kevin no 8.0
9 1 Jonas yes 19.0

Sample Solution:

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
df = [Link](exam_data)
print("Original DataFrame")
print(df)
df = [Link](0)
print("\nNew DataFrame replacing all NaN with 0:")
print(df)

Expected output:

Original DataFrame
name score attempts qualify
0 Anastasia 12.5 1 yes
1 Dima 9.0 3 no
2 Katherine 16.5 2 yes
3 James NaN 3 no
4 Emily 9.0 2 no
5 Michael 20.0 3 yes
6 Matthew 14.5 1 yes
7 Laura NaN 1 no
8 Kevin 8.0 2 no
9 Jonas 19.0 1 yes

New DataFrame replacing all NaN with 0:


name score attempts qualify
0 Anastasia 12.5 1 yes
1 Dima 9.0 3 no
2 Katherine 16.5 2 yes
3 James 0.0 3 no
4 Emily 9.0 2 no
5 Michael 20.0 3 yes
6 Matthew 14.5 1 yes
7 Laura 0.0 1 no
8 Kevin 8.0 2 no
9 Jonas 19.0 1 yes

9. Write a Pandas program to drop a 2nd and 4th rows from a specified DataFrame.

Sample data:
Original DataFrame
col1 col2 col3
0147
1458
2369
3470
4581

Sample Solution:
import pandas as pd
import numpy as np
d = {'col1': [1, 4, 3, 4, 5], 'col2': [4, 5, 6, 7, 8], 'col3': [7, 8, 9, 0, 1]}
df = [Link](d)
print("Original DataFrame")
print(df)
print("New DataFrame after removing 2nd & 4th rows:")
df = [Link]([Link][[2,4]])
print(df)

New DataFrame after removing 2nd & 4th rows:


col1 col2 col3
0147
1458
3470

10. Write Python code to change the data from a file [Link] into uppercase, save the
result in file [Link] and display the contents of file2

fp=open("[Link]", "r")
fp1=open("[Link]", "w")
for line in fp:
l=[Link]("\n")
for i in l:
w=''.join(i)
[Link]([Link]())
[Link]('\n')
fp1=open("[Link]", "r")
print([Link]())
[Link]()

11. Write a python code to reverse the contents of input file([Link]) and store it in another
file and display its contents
f1 = open("[Link]", "w")
f=open("[Link]", "r")
data=[Link]()
[Link](data[::-1])
[Link]()
f1=open("[Link]", "r")
print([Link]())
[Link]()

12. Given an input file([Link]), find the longest word in the file.

def longest_word(filename):
with open(filename, 'r') as infile:
words = [Link]().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]

print(longest_word('[Link]'))

[Link] a program to count the number of upper-case alphabets present in a text file
“[Link]”

def uppercount():
upper=0
f1=open("[Link]",'r')
line=[Link]()
for i in line:
if ([Link]() == True):
upper+=1
print("Total no. of uppercase alphabets :",upper)
uppercount()

14. Write a program to display all the lines in a file “[Link]” along with line/record
number.

fh=open("[Link]","r")
count=0
lines=[Link]()
for a in lines:
count=count+1
print(count,a)
[Link]()

Difficulty(total 15)

1.
#### to count number of words, characters, lines from a text file
[Link]

nlines=0
nchars=0
nwords=0
f=open("[Link]","r")
for line in f:
l=[Link]("\n")
nlines+=1
w=[Link]()
nwords+=len(w)
nchars+=len(l)
print("no of lines=",nlines)
print("no of characters=",nchars)
print("no of words=",nwords)

input:
contents of [Link]:
Python supports both object-oriented and procedure-oriented programming
Python is Free and Open-Source

Output:
no of lines= 2
no of characters= 101
no of words= 12
2.

#### from a given file [Link] of integers,


### write even numbers into seperate file and print file contents

fp = open("[Link]","r")
evenfp = open("[Link]","w")
#oddfp = open("[Link]","w")
for ele in fp:
[Link]("\n")
ele=[Link]()
for i in ele:
elem = int(i)
if elem % 2 == 0:
[Link](str(elem))
[Link](" ")
#else:
#[Link](str(elem))
#[Link](" ")
[Link]()
#[Link]()
evenfp = open("[Link]","r")
print([Link]())
[Link]()

input:
[Link] contents:
10 35 22 89 100 57 34 56 78 2

Output:
10 22 100 34 56 78 2

3.
### to arrange the words of each line of a file [Link] in alphabetical
order and write those words into another file, also print the resulting
file contents
f=open("[Link]","r")
fp=open("[Link]","w")
for line in f:
l=[Link]("\n")
w=[Link]()
#print(w)
[Link]()
for i in w:
[Link](i)
[Link](" ")
[Link]("\n")
[Link]()
fp=open("[Link]","r")
print([Link]())

input:
[Link] contents
good morning welcome to python class
practice well

output:
class good morning python to welcome
practice well

4. Write a Pandas program to add, subtract, multiple and divide two Pandas Series.

Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 9]

import pandas as pd
ds1 = [Link]([2, 4, 6, 8, 10])
ds2 = [Link]([1, 3, 5, 7, 9])
ds = ds1 + ds2
print("Add two Series:")
print(ds)
print("Subtract two Series:")
ds = ds1 - ds2
print(ds)
print("Multiply two Series:")
ds = ds1 * ds2
print(ds)
print("Divide Series1 by Series2:")
ds = ds1 / ds2
print(ds)

Sample Output:

Add two Series:


0 3
1 7
2 11
3 15
4 19
dtype: int64
Subtract two Series:
0 1
1 1
2 1
3 1
4 1
dtype: int64
Multiply two Series:
0 2
1 12
2 30
3 56
4 90
dtype: int64
Divide Series1 by Series2:
0 2.000000
1 1.333333
2 1.200000
3 1.142857
4 1.111111
dtype: float64

5. Write a Pandas program to add one row in an existing DataFrame.


Sample data:

Original DataFrame
col1 col2 col3
0 1 4 7
1 4 5 8
2 3 6 9
3 4 7 0
4 5 8 1
After add one row:
col1 col2 col3
0 1 4 7
1 4 5 8
2 3 6 9
3 4 7 0
4 5 8 1
5 10 11 12
6. Write a Pandas program to calculate the mean score for each different student in data
frame.

Sample DataFrame:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Sample Solution:

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = [Link](exam_data , index=labels)
print("Mean score for each different student in data frame:")
print(df['score'].mean())

Expected Output:
Mean score for each different student in data frame:
13.5625

7.
Given is a dataframe showing the name, occupation, salary of people. Find the
Mean and median salary per occupation
import pandas as pd
dic1={ 'name':['abc','pqr','wx','rs','ppp','sss','aaa'],
'occupation':['officer', 'clerk', 'officer','professor','programmer',
'clerk','officer'],
'salary':[10000,20000,5000, 60000, 10000, 20000, 40000] }
df= [Link](dic1)
print([Link]('occupation').agg({'salary':'mean'}))
print([Link]('occupation').agg({'salary':'median'}))

output:
Mean:
salary
occupation
clerk 20000.000000
officer 18333.333333
professor 60000.000000
programmer 10000.000000

Median:
salary
occupation
clerk 20000.0
officer 10000.0
professor 60000.0
programmer 10000.0

8.
Write a Pandas program to count the number of rows and columns of a
DataFrame.
import pandas as pd
dic1={ 'name':['abc','pqr','wx','rs','ppp','sss','aaa'],
'occupation':['officer', 'clerk', 'officer','professor','programmer',
'clerk','officer'],
'salary':[10000,20000,5000, 60000, 10000, 20000, 40000]}

df= [Link](dic1)

total_rows=len([Link][0])
total_cols=len([Link][1])
print("Number of Rows: "+str(total_rows))
print("Number of Columns: "+str(total_cols))

output:
Number of Rows: 7
Number of Columns: 3

9. Write a Pandas program to sort the data frame first by 'name' in


descending order, then by 'salary' in ascending order.
import pandas as pd
dic1={ 'name':['abc','pqr','wx','rs','ppp','sss','aaa'],
'occupation':['officer', 'clerk', 'officer','professor','programmer',
'clerk','officer'],
'salary':[10000,20000,5000, 60000, 10000, 20000, 40000]}
df= [Link](dic1)
df=df.sort_values(by=['name', 'salary'], ascending=[False, True])
print("After sorting:")
print(df)

output:
After sorting:
name occupation salary
2 wx officer 5000
5 sss clerk 20000
3 rs professor 60000
1 pqr clerk 20000
4 ppp programmer 10000
0 abc officer 10000
6 aaa officer 40000

10.
Write a Pandas program to write a DataFrame to CSV file using tab
separator.
import pandas as pd
import numpy as np
d = {'col1': [11, 22, 33, 44, 55], 'col2': [40, 50, 60, 70, 80],
'col3': [7, 8, 9, 10, 1]}
df = [Link](data=d)
print("Original DataFrame")
print(df)
print('Data from new_file.csv file:')
df.to_csv('new_file.csv', sep='\t', index=False)
new_df = pd.read_csv('new_file.csv')
print(new_df)

output:
Original DataFrame
col1 col2 col3
0 11 40 7
1 22 50 8
2 33 60 9
3 44 70 10
4 55 80 1
Data from new_file.csv file:
col1\tcol2\tcol3
0 11\t40\t7
1 22\t50\t8
2 33\t60\t9
3 44\t70\t10
4 55\t80\t1

Sqlite3

1. Create a database University , which contains teacher table (Tid,Tname


,subject) and student (sid,sname marks, branch)

Tid,sid is a primary key. All the values must not be [Link] the table contents
in column format and save it in [Link] and [Link] files

2. Write a query to get unique department ID from employee table


Employee(eid,ename ,designation,department ID,Salary)

3. Write a query to get all employee details from the employee table order
by first name, descending
Employee(eid,ename ,designation,department ID,Salary)

4. Write a query to get the average salary and number of employees in the
employees [Link](eid,ename ,designation,department
ID,Salary)

5. Write a query to display the names (first_name, last_name) and salary for
all employees whose salary is not in the range $10,000 through $15,000 and
are in department 30 or 100

Employee(eid,ename ,designation,department ID,Salary)


6. Write a query to display the names (first_name, last_name) and salary for
all employees whose salary is not in the range $10,000 through $15,000.
7. Write a Python program to create a table and insert some records in that
table. Finally selects all rows from the table and display the records

Student(Name,Id,Section,Branch,Marks)

Id must be a primary key

other attributes should not have null values.

8. Write a Python program to update the mark of the student whose Id is 20 in


the given table and select all rows before and after updating the said table

Student(Name,Id,Section,Branch,Marks)

Id must be a primary key

other attributes should not have null values.

Note: Assume that above student table is available with the data.

9. Write a Python program to delete details of a student whose name is


"KIRAN". print the table contents before and after deletion of the data.

Student(Name,Id,Section,Branch,Marks)

Id must be a primary key


other attributes should not have null values.

Note: Assume that the above table is available with data.

10. Write a SQLite program to find sum, average, minimum mark and maximum
mark of the class.

Student(Name,Id,Section,Branch,Marks)

Id must be a primary key

other attributes should not have null values.

Note: Assume that the above table is available with data.

Regular Expressions

1. Write a Python program that matches a string that has an a followed by


two to three 'b'
2. Write a Python program that matches a word at the beginning of a
string

Eg:string-Python Programming pattern-Python

3. Write a Python program to match a string that contains only upper and
lowercase letters, numbers, and underscores.
4. Write a Python program to replace whitespaces with an underscore and
vice versa.
5. Write a Python program to separate and print the numbers of a given
string
6. Write a function that returns the following in the given paragraph
a. number of words
b. number of articles (a, an, the)
7. Write a function that replaces comma, semicolon, dot and space with a
colon.
8. Write a function that returns a string with words of length less than
five in the input string.

9. Write a function that finds the words ending with a vowel , in the input
string.
[Link] a function that returns a string after replacing 1 with True and 0
with False, in the input string.
[Link] a function that returns number of special characters($ , %, ?, #, !
) in the input string.
[Link] a function that returns a string after capitalizing the first
character of each word, in the input string.
[Link]='From [Link]@[Link] Sat Jan 5 09:14:16 2008'
Write a regular expression that extracts timestamp from the above string
output: 09:14:16
[Link] a Python program that matches a string that has an a followed by
zero or more b's
[Link] a Python program that matches a string that has an a followed by one or
more b's
[Link] a Python program that matches a string that has an a followed by zero or
one 'b'
[Link] a Python program that matches a string that has an a followed by
three 'b'
[Link] a Python program to find sequences of lowercase letters joined with
an underscore
19. Write a Python program to find the occurrence and position of the substrings
within a string.
input:
'Python exercises, PHP exercises, C# exercises'
output:
Found "exercises" at 7:16
Found "exercises" at 22:31
Found "exercises" at 36:45

20. Write a Python program to abbreviate 'Road' as 'Rd.' in a given string.


input:
'21 Ramkrishna Road'
output:
21 Ramkrishna Rd.
21. Write a Python program to find all three, four, five characters long words in a
string.
Input:
'The quick brown fox jumps over the lazy dog.'
Output:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
22. WAP to find the given character appear in the given string or not
how many times the given list of characters appeared in the string
string:" The ai can predict rain in Spain city"
pattern :a,c,p
23. . WAP to find no of times given word appears in a string using regular expressions
String="progrmming with c proramming with python progamming languages"
Pattern="prog"
24. . Write a Python program to find all words starting with 'a' or 'e' in a given string.

String: "The following example creates an Array List with a capacity of 50 elements"

Output: ['example', 'an', 'elements']Write a Python program to separate and print the numbers of a
given string

25. Write a Python program that matches a string that has an a followed by two to three
'b'
String: ab

26. Wite a query to display the first_name of all employees who have both an "b" and
"c" in their first name.

Employee(eid,ename ,designation,department ID,Salary)


Matplotlib

1. Write a python program to draw a line plot between month and profit .
Name x-axis as months, Y-axis as months, title of the graph is profit
analysis

2. Write a Python program to plot two or more lines where each line talks about
the profits of a particular product in each month give different colors to each
line name the lines with the name of the product using legend.

3. Write a Python program to Read no of products sold in each month and show
it using a bar graph.
4. Write a Python program to Calculate total sale data for last year for
each product and show it using a Pie chart
5. Write a Python program to Read different product sales data and show
it using the stack or area plot
6. Write a Python program to Read any two products sales data and
show it using the bar chart
7. Draw a graph to find no of people fall under a given range of age groups
a. input- list of age ranges
b. Table of contents (name , age, phone no)
8. Write a Python program to Calculate total sale data for last year for each
product and show it using a Pie chart
product -laptop, mobile, TV, Washing machine, Fridge

Note: In Pie chart display Number of units sold per year for each product
in percentage

User Defined Packages, test cases

1. write test cases for checking method cuboid.


a. cuboid_volume(2,8)
b. cuboid_volume(1,1)
c. cuboid_volume(0,0)
d. cuboid_volume(5.5,166.375)
MID2 Questions( Strings, Dictionaries from module 2 and all topics of Module3)

Please paste questions according to the category

Easy(total 15)
1. You are given two synonym dictionary file parse through each file line by line and
retrieve the data each line will be a word with its synonyms in this format

responsibility - authority, control, leadership


your task is to form a dictionary which looks like the below one

d = {"responsibility" : ["authority", "control", "leadership"]}


Hint:
9Read the file line by line as strings into a list lst
Replace space and '-' ' -' with ',' and '\n' with nothing ''
Take the ith string from the list lst and split them as templst
make the0th them of templst as key and remaining as list of values
[Link] the 4th step by going through the other terms of templst and appending them into
the dictionary key
Repeate the steps 3 and 5 until the len of lst

2.
# to write a list to a file [Link] and display the contents of file4
l=[1,20.5,['abc',4],"hello"]
f = open("[Link]","w")
[Link](str(l))
f = open("[Link]","r")
print([Link]())

input:

output:
[1,20.5,['abc',4],"hello"]

3.
# to write a dictionary to a file and display the contents of a file
d={1:"one", 2:"two", 3:"three",'a':['abc', 'bcd']}
f = open("[Link]","w")
for i in [Link]():
[Link](str(i))
f = open("[Link]","r")
print([Link]())
input:
{1:"one", 2:"two", 3:"three",'a':['abc', 'bcd']}
output:
(1, 'one')(2, 'two')(3, 'three')('a', ['abc', 'bcd'])
4.
#### to read n lines from a file [Link]
fp = open("[Link]","r")
n=int(input())
for j in range(n):
print([Link]().strip("\n"))

input:
3
[Link] contents:
("Hello", "World")
[Good Morning]
(Welcome to Python Class)
Complete the assignment
“Due date for submission is tomorrow”

output:
("Hello", "World")
[Good Morning]
(Welcome to Python Class)

5.
### to merge two dictionaries into a single one
s1=input()
s2=input()
dict1=eval(s1)
dict2=eval(s2)
[Link](dict2)
print(dict1)

input:
{'x': 10, 'y': 8}
{'a': 6, 'b': 4}

Output:
{'x': 10, 'y': 8, 'a': 6, 'b': 4}

6. Write a Pandas program to convert a Panda module Series to Python list


and it’s type.
Sample Solution:
import pandas as pd
ds = [Link]([2, 4, 6, 8, 10])
print("Pandas Series and type")
print(ds)
print(type(ds))
print("Convert Pandas Series to Python list")
print([Link]())
print(type([Link]()))

Pandas Series and type


0 2
1 4
2 6
3 8
4 10
dtype: int64

Convert Pandas Series to Python list


[2, 4, 6, 8, 10]

7. Write a Pandas program to create and display a DataFrame from a


specified dictionary data which has the index labels.

Sample Python dictionary data and list labels:


exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily',
'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no',
'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Expected Output:
name score attempts qualify
a Anastasia 12.5 1 yes
b Dima 9.0 3 no
c Katherine 16.5 2 yes
d James NaN 3 no
e Emily 9.0 2 no
f Michael 20.0 3 yes
g Matthew 14.5 1 yes
h Laura NaN 1 no
i Kevin 8.0 2 no
j Jonas 19.0 1 yes
8. Write a Python script to add a key to a dictionary.
Sample Solution:
d = {0:10, 1:20}
print(d)
[Link]({2:30})
print(d)

Expected output:
{0: 10, 1: 20}
{0: 10, 1: 20, 2: 30}

9. Write a Python script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are square of keys.
Sample Solution:
d=dict()
for x in range(1,16):
d[x]=x**2
print(d)

Expected output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11:
121, 12: 144, 13: 169, 14: 196, 15: 225}

10. Write a Python program to sum all the items in a dictionary.


Sample Solution:

my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))

Sample Output: 293

11. Write a Pandas program to convert a given list of lists into a


Dataframe.
Sample Solution:
import pandas as pd
my_lists = [['col1', 'col2'], [2, 4], [1, 3]]
# sets the headers as list
headers = my_lists.pop(0)
print("Original list of lists:")
print(my_lists)
df = [Link](my_lists, columns = headers)
print("New DataFrame")
print(df)

Expected output:
New DataFrame:
col1 col2
0 2 4
1 1 3

12. Accept five names from the user and write in a file “[Link]” and display them

f = open("[Link]","w")
for i in range(5):
n = input()
[Link](n)
[Link]("\n")
[Link]()
f = open("[Link]","r")
print([Link]())

[Link] python code to merge two dictionaries into a single one.

s1=input()
s2=input()
dict1=eval(s1)
dict2=eval(s2)
[Link](dict2)
print(dict1)

14. Write a program in python to display number of lines in a file(“[Link]”).

f=open("[Link]","r")
l=[Link]()
print(len(l))
Moderate(total 15)

1. You will be given a text file like the below one

Visakhapatnam City
Tanali Town
Mumbai City
Kodavatikallu Village
Maavooru Village
Anantapuram Town
your task is to form a dictionary which looks like this

{'City':['Visakhapatnam', 'Mumbai'], 'Town':['Tanali', 'Anantapuram'], 'Village':['Kodavatikallu',


'Maavooru']}
Hint:

1. Read each line into a list lst as strings


2. Next split ith index string in list lst into a templst where you will visualize them as two
seperate strings as shown below
['Visakhapatnam', 'City']
[Link] the second term as key and first term as values
4. As key cannot be duplicated check if the key is already there or not. I there append the found
value or create a new key
Repeate the steps 2-4 until the len of list ls

2.
### to copy the contents of a file [Link] into [Link] and display
the contents of file2.
fp=open("[Link]", "r")
fp1=open("[Link]", "w")
for line in fp:
[Link](line)
[Link]()
[Link]()
fp1=open("[Link]", "r")
print([Link]())
[Link]()

input:
[Link] contents:
GOOD MORNING
COMPLETE THE ASSIGNMENT
DUE DATE FOR SUBMISSION IS TOMORROW

Output:
GOOD MORNING
COMPLETE THE ASSIGNMENT
DUE DATE FOR SUBMISSION IS TOMORROW

3.
### to change the data from a file [Link] into uppercase,
### save the result in file [Link]
### and display the contents of file2
fp=open("[Link]", "r")
fp1=open("[Link]", "w")
for line in fp:
l=[Link]("\n")
for i in l:
w=''.join(i)
[Link]([Link]())
[Link]('\n')
fp1=open("[Link]", "r")
print([Link]())
[Link]()

input:
("Hello", "World")
[Good Morning]
(Welcome to Python Class)

Output:
("HELLO", "WORLD")
[GOOD MORNING]
(WELCOME TO PYTHON CLASS)

4.
# from a given file [Link], join the strings of each line of a file and
# write the result into another file [Link], also display the contents
# of file2.
f=open("[Link]","r")
fp=open("[Link]","w")
for line in f:
l=[Link]("\n")
w=[Link]()
w="".join(w)
[Link](w)
[Link]("\n")
fp=open("[Link]","r")
print([Link]())

input:
[Link] contents:
good morning
welcome to class

output:
goodmorning
welcometoclass

5.
# to convert a string of key value pairs to a dictionary

# input a String
string = input()

# eval() convert string to dictionary


Dict = eval(string)
print(Dict)

input:
{'one':10, 'two':20, 'three':30}

Output:
{'one':10, 'two':20, 'three':30}

input:
{10:'one', 20:'two', 30:'three'}

Output:
{10:'one', 20:'two', 30:'three'}

6. Write a Pandas program to convert a dictionary to a Pandas series.


Sample dictionary: d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}

Sample Solution:
import pandas as pd
d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}
print("Original dictionary:")
print(d1)
new_series = [Link](d1)
print("Converted series:")
print(new_series)

Converted series:
a 100
b 200
c 300
d 400
e 800
dtype: int64

7. Write a Pandas program to get the first 3 rows of a given DataFrame.

Sample DataFrame:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Sample solution:
import pandas as pd
import numpy as np

exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',


'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

df = [Link](exam_data , index=labels)
print("First three rows of the data frame:")
print([Link][:3])

Expected output:
First three rows of the data frame:
name score attempts qualify
a Anastasia 12.5 1 yes
b Dima 9.0 3 no
c Katherine 16.5 2 yes
8. Write a Pandas program to replace all the NaN values with Zero's in a column of a
dataframe.

Original DataFrame:

Sample data:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0
2 2 Katherine yes 16.5
3 3 James no NaN
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no NaN
8 2 Kevin no 8.0
9 1 Jonas yes 19.0
New DataFrame replacing all NaN with 0:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0
2 2 Katherine yes 16.5
3 3 James no 0.0
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no 0.0
8 2 Kevin no 8.0
9 1 Jonas yes 19.0

Sample Solution:

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
df = [Link](exam_data)
print("Original DataFrame")
print(df)
df = [Link](0)
print("\nNew DataFrame replacing all NaN with 0:")
print(df)

Expected output:

Original DataFrame
name score attempts qualify
0 Anastasia 12.5 1 yes
1 Dima 9.0 3 no
2 Katherine 16.5 2 yes
3 James NaN 3 no
4 Emily 9.0 2 no
5 Michael 20.0 3 yes
6 Matthew 14.5 1 yes
7 Laura NaN 1 no
8 Kevin 8.0 2 no
9 Jonas 19.0 1 yes

New DataFrame replacing all NaN with 0:


name score attempts qualify
0 Anastasia 12.5 1 yes
1 Dima 9.0 3 no
2 Katherine 16.5 2 yes
3 James 0.0 3 no
4 Emily 9.0 2 no
5 Michael 20.0 3 yes
6 Matthew 14.5 1 yes
7 Laura 0.0 1 no
8 Kevin 8.0 2 no
9 Jonas 19.0 1 yes

9. Write a Pandas program to drop a 2nd and 4th rows from a specified DataFrame.

Sample data:
Original DataFrame
col1 col2 col3
0147
1458
2369
3470
4581

Sample Solution:
import pandas as pd
import numpy as np
d = {'col1': [1, 4, 3, 4, 5], 'col2': [4, 5, 6, 7, 8], 'col3': [7, 8, 9, 0, 1]}
df = [Link](d)
print("Original DataFrame")
print(df)
print("New DataFrame after removing 2nd & 4th rows:")
df = [Link]([Link][[2,4]])
print(df)

New DataFrame after removing 2nd & 4th rows:


col1 col2 col3
0147
1458
3470

10. Write Python code to change the data from a file [Link] into uppercase, save the
result in file [Link] and display the contents of file2

fp=open("[Link]", "r")
fp1=open("[Link]", "w")
for line in fp:
l=[Link]("\n")
for i in l:
w=''.join(i)
[Link]([Link]())
[Link]('\n')
fp1=open("[Link]", "r")
print([Link]())
[Link]()

11. Write a python code to reverse the contents of input file([Link]) and store it in another
file and display its contents
f1 = open("[Link]", "w")
f=open("[Link]", "r")
data=[Link]()
[Link](data[::-1])
[Link]()
f1=open("[Link]", "r")
print([Link]())
[Link]()

12. Given an input file([Link]), find the longest word in the file.

def longest_word(filename):
with open(filename, 'r') as infile:
words = [Link]().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]

print(longest_word('[Link]'))

[Link] a program to count the number of upper-case alphabets present in a text file
“[Link]”

def uppercount():
upper=0
f1=open("[Link]",'r')
line=[Link]()
for i in line:
if ([Link]() == True):
upper+=1
print("Total no. of uppercase alphabets :",upper)
uppercount()

14. Write a program to display all the lines in a file “[Link]” along with line/record
number.

fh=open("[Link]","r")
count=0
lines=[Link]()
for a in lines:
count=count+1
print(count,a)
[Link]()

Difficulty(total 15)

1.
#### to count number of words, characters, lines from a text file
[Link]

nlines=0
nchars=0
nwords=0
f=open("[Link]","r")
for line in f:
l=[Link]("\n")
nlines+=1
w=[Link]()
nwords+=len(w)
nchars+=len(l)
print("no of lines=",nlines)
print("no of characters=",nchars)
print("no of words=",nwords)

input:
contents of [Link]:
Python supports both object-oriented and procedure-oriented programming
Python is Free and Open-Source

Output:
no of lines= 2
no of characters= 101
no of words= 12

2.

#### from a given file [Link] of integers,


### write even numbers into seperate file and print file contents

fp = open("[Link]","r")
evenfp = open("[Link]","w")
#oddfp = open("[Link]","w")
for ele in fp:
[Link]("\n")
ele=[Link]()
for i in ele:
elem = int(i)
if elem % 2 == 0:
[Link](str(elem))
[Link](" ")
#else:
#[Link](str(elem))
#[Link](" ")
[Link]()
#[Link]()
evenfp = open("[Link]","r")
print([Link]())
[Link]()

input:
[Link] contents:
10 35 22 89 100 57 34 56 78 2

Output:
10 22 100 34 56 78 2

3.
### to arrange the words of each line of a file [Link] in alphabetical
order and write those words into another file, also print the resulting
file contents
f=open("[Link]","r")
fp=open("[Link]","w")
for line in f:
l=[Link]("\n")
w=[Link]()
#print(w)
[Link]()
for i in w:
[Link](i)
[Link](" ")
[Link]("\n")
[Link]()
fp=open("[Link]","r")
print([Link]())

input:
[Link] contents
good morning welcome to python class
practice well

output:
class good morning python to welcome
practice well

4. Write a Pandas program to add, subtract, multiple and divide two Pandas Series.

Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 9]

import pandas as pd
ds1 = [Link]([2, 4, 6, 8, 10])
ds2 = [Link]([1, 3, 5, 7, 9])
ds = ds1 + ds2
print("Add two Series:")
print(ds)
print("Subtract two Series:")
ds = ds1 - ds2
print(ds)
print("Multiply two Series:")
ds = ds1 * ds2
print(ds)
print("Divide Series1 by Series2:")
ds = ds1 / ds2
print(ds)

Sample Output:

Add two Series:


0 3
1 7
2 11
3 15
4 19
dtype: int64
Subtract two Series:
0 1
1 1
2 1
3 1
4 1
dtype: int64
Multiply two Series:
0 2
1 12
2 30
3 56
4 90
dtype: int64
Divide Series1 by Series2:
0 2.000000
1 1.333333
2 1.200000
3 1.142857
4 1.111111
dtype: float64

5. Write a Pandas program to add one row in an existing DataFrame.


Sample data:
Original DataFrame
col1 col2 col3
0 1 4 7
1 4 5 8
2 3 6 9
3 4 7 0
4 5 8 1
After add one row:
col1 col2 col3
0 1 4 7
1 4 5 8
2 3 6 9
3 4 7 0
4 5 8 1
5 10 11 12

6. Write a Pandas program to calculate the mean score for each different student in data
frame.

Sample DataFrame:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Sample Solution:

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = [Link](exam_data , index=labels)
print("Mean score for each different student in data frame:")
print(df['score'].mean())

Expected Output:
Mean score for each different student in data frame:
13.5625
7.
Given is a dataframe showing the name, occupation, salary of people. Find the
Mean and median salary per occupation
import pandas as pd
dic1={ 'name':['abc','pqr','wx','rs','ppp','sss','aaa'],
'occupation':['officer', 'clerk', 'officer','professor','programmer',
'clerk','officer'],
'salary':[10000,20000,5000, 60000, 10000, 20000, 40000] }
df= [Link](dic1)
print([Link]('occupation').agg({'salary':'mean'}))
print([Link]('occupation').agg({'salary':'median'}))

output:
Mean:
salary
occupation
clerk 20000.000000
officer 18333.333333
professor 60000.000000
programmer 10000.000000

Median:
salary
occupation
clerk 20000.0
officer 10000.0
professor 60000.0
programmer 10000.0

8.
Write a Pandas program to count the number of rows and columns of a
DataFrame.
import pandas as pd
dic1={ 'name':['abc','pqr','wx','rs','ppp','sss','aaa'],
'occupation':['officer', 'clerk', 'officer','professor','programmer',
'clerk','officer'],
'salary':[10000,20000,5000, 60000, 10000, 20000, 40000]}

df= [Link](dic1)

total_rows=len([Link][0])
total_cols=len([Link][1])
print("Number of Rows: "+str(total_rows))
print("Number of Columns: "+str(total_cols))
output:
Number of Rows: 7
Number of Columns: 3

9. Write a Pandas program to sort the data frame first by 'name' in


descending order, then by 'salary' in ascending order.
import pandas as pd
dic1={ 'name':['abc','pqr','wx','rs','ppp','sss','aaa'],
'occupation':['officer', 'clerk', 'officer','professor','programmer',
'clerk','officer'],
'salary':[10000,20000,5000, 60000, 10000, 20000, 40000]}

df= [Link](dic1)
df=df.sort_values(by=['name', 'salary'], ascending=[False, True])
print("After sorting:")
print(df)

output:
After sorting:
name occupation salary
2 wx officer 5000
5 sss clerk 20000
3 rs professor 60000
1 pqr clerk 20000
4 ppp programmer 10000
0 abc officer 10000
6 aaa officer 40000

10.
Write a Pandas program to write a DataFrame to CSV file using tab
separator.
import pandas as pd
import numpy as np
d = {'col1': [11, 22, 33, 44, 55], 'col2': [40, 50, 60, 70, 80],
'col3': [7, 8, 9, 10, 1]}
df = [Link](data=d)
print("Original DataFrame")
print(df)
print('Data from new_file.csv file:')
df.to_csv('new_file.csv', sep='\t', index=False)
new_df = pd.read_csv('new_file.csv')
print(new_df)

output:
Original DataFrame
col1 col2 col3
0 11 40 7
1 22 50 8
2 33 60 9
3 44 70 10
4 55 80 1
Data from new_file.csv file:
col1\tcol2\tcol3
0 11\t40\t7
1 22\t50\t8
2 33\t60\t9
3 44\t70\t10
4 55\t80\t1
1. Write a python program to draw a line plot between month and profit .

Name x-axis as months, Y-axis as months, title of the graph is profit analysis

2. Write a Python program to plot two or more lines where each line talks about the profits
of a particular product in each month give different colors to each line name the lines with
the name of the product using legend.

3. Write a Python program to Read no of products sold in each month and show it using a
bar graph.

4. Write a Python program to Calculate total sale data for last year for each product and
show it using a Pie chart

5. Write a Python program to Read different product sales data and show it using the stack
or area plot

6. Write a Python program to Read any two products sales data and show it using the bar
chart

7. Draw a graph to find no of people fall under a given range of age groups

1. input- list of age ranges


2. Table of contents (name , age, phone no)

8. Write a Python program to Calculate total sale data for last year for each product and
show it using a Pie chart

product -laptop, mobile, TV, Washing machine, Fridge

Note: In Pie chart display Number of units sold per year for each product in percentage

9. Write a python program to append the following content to a file.(Do not overwrite)

Given file : [Link]


Append the following content(three lines):
This is QUIZ3
Examination
Of python programming

10. Read the csv file and count the number of student who scored CGPA 9 and more than
9. file name: [Link]

11. Read the given csv file and display the maximum [Link] name: [Link]

12. Read the given csv file and display the maximum [Link] name: [Link]

13. Write a python program to count number of lines in a given [Link] name : [Link]

14. Write a python program to count number of words in a [Link] name: [Link]

[Link] a function that returns a string with words of length less than five in the input
string.

[Link] a function that finds the words ending with a vowel , in the input string.

17. Write a function that returns a string after replacing 1 with True and 0 with False, in the
input string.

18. Write a function that returns number of special characters($ , %, ?, #, ! ) in the input
string.

19. Write a function that returns a string after capitalizing the first character of each word,
in the input string.

20. String='From [Link]@[Link] Sat Jan 5 09:14:16 2008'

Write a regular expression that extracts timestamp from the above string output: 09:14:16
21. Write a Python program that matches a string that has an a followed by zero or more b's
22. Write a Python program that matches a string that has an a followed by one or more b's

23. To write a list to a file and display the contents of the file.

24. Write a Python program that matches a string that has an a followed by zero or one 'b'

25. Accept five names from the user and write in a file “[Link]” and display them

26. Write a Python program that matches a string that has an a followed by zero or one 'b'

27. To read n lines from a file named as [Link]

28. To write a dictionary to a file and display the contents of the file.

29. Write a Python program to find the occurrence and position of the substrings within a
string.

input:
'Python exercises, PHP exercises, C# exercises'
output:
Found "exercises" at 7:16
Found "exercises" at 22:31
Found "exercises" at 36:45

30. Write python code to merge two dictionaries into a single one.

31. Write a Python script to print a dictionary where the keys are numbers between 1 and N
(both included) and the values are square of keys.

32. Write a Python program to find sequences of lowercase letters joined with an
underscore
33. write a Python program to abbreviate 'Road' as 'Rd.' in a given string.
input:
'21 Ramkrishna Road'
output:
21 Ramkrishna Rd.

34. Write a Python program to sum all the values in (key, value) pairs of a dictionary.(values
to be taken as integers)
ex:
d={ 1:10, 2:20, 3:30 }
output: 60
d={'one':1, 'two':2, 'three': 3}
output: 6

35. Write a Python program to find all three, four, five characters long words in a string.
Input:
'The quick brown fox jumps over the lazy dog.'
Output:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

36. Write a Pandas program to create and display a DataFrame from a dictionary.

37. Write a Pandas program to covert dictionary into Series data structure.
ex:
input: {1:"one", 2:"two", 3:"three",'a':['abc', 'bcd']}
output:
1 one
2 two
3 three
a [abc, bcd]
dtype: object
38. Write a program in python to display number of lines in a file(“[Link]”).
39. Write a Python program that matches a string that has an a followed by two to three 'b'
String: ab
output: Not Matched
String: aabbbbbc
output: Found a Match
40. Write a Python program to replace whitespaces with an underscore and vice versa.
String: Python Exercises
Python_Exercises

[Link] a Python program to separate and print the numbers of a given string
String: Ten 10, Twenty 20, Thirty 30

Output: 10 20 30

42. Write a Python program to match a string that contains only upper and lowercase
letters, numbers, and underscores.

43. Write a Python program that matches a word at the beginning of a string
Eg:string-Python Programming pattern-Python

44. Create a database University , which contains teacher table (Tid,Tname ,subject) and
student (sid,sname marks, branch)
Tid,sid is a primary key. All the values must not be [Link] the table contents in column
format and save it in [Link] and [Link] files
45. Write a SQLite program to find sum, average, minimum mark and maximum mark of the
class.
Student(Name,Id,Section,Branch,Marks)
Id must be a primary key
other attributes should not have null values.
Note: Assume that the above table is available with data.

46. Write a query to get unique department ID from employee table Employee(eid,ename
,designation,department ID,Salary)
47. Write a query to get all employee details from the employee table order by first name,
descending
Employee(eid,ename ,designation,department ID,Salary)
48\. Write a query to get all employee details from the employee table order by first name,
descending
Employee(eid,ename ,designation,department ID,Salary)
49. Write a query to display the names (first_name, last_name) and salary for all employees
whose salary is not in the range $10,000 through $15,000 and are in department 30 or 100
Employee(eid,ename ,designation,department ID,Salary)
50. Write a query to display the names (first_name, last_name) and salary for all employees
whose salary is not in the range $10,000 through $15,000.
51. Write a Python program to create a table and insert some records in that table. Finally
selects all rows from the table and display the records
Student(Name,Id,Section,Branch,Marks)
Id must be a primary key
other attributes should not have null values.
[Link] a Python program to update the mark of the student whose Id is 20 in the given
table and select all rows before and after updating the said table
Student(Name,Id,Section,Branch,Marks)
Id must be a primary key
other attributes should not have null values.
Note: Assume that above student table is available with the data.
53. Write a Python program to delete details of a student whose name is "KIRAN". print the
table contents before and after deletion of the data.
Student(Name,Id,Section,Branch,Marks)
Id must be a primary key
other attributes should not have null values.
Note: Assume that the above table is available with data.
54. convert given KG into pound
1kg = 2.204
55. covert F to C degrees c = 5/9(F-32)
input:54
output:12.22
input:78
output:25.55
56. covert F to C degrees c = 5/9(F-32)
input:54
output:12.22
input:78
output:25.55
57. Find the gcd of 450,156.
58. count number of words in a string
59. Python Program To Find ASCII value of a character

60. Write Python code to change the data from a file [Link] into uppercase, save the result
in file [Link] and display the contents of file2

61. Write Python code to change the data from a file [Link] into uppercase, save the result
in file [Link] and display the contents of file2

For example:

Tes Input Result


t

1 ("Hello", "World") ("HELLO", "WORLD")


[Good Morning] [GOOD MORNING]
(Welcome to Python (WELCOME TO PYTHON CLASS)
Class) COMPLETE THE ASSIGNMENT
"DUE DATE FOR SUBMISSION IS
TOMORROW"

62. Write a python code to reverse the contents of input file([Link]) and store it in another
file and display its contents

63. Write a python code to reverse the contents of input file([Link]) and store it in another
file and display its contents
For example:
Tes Input Result
t

1 good morning ssalc ot


welcome to emoclew
class gninrom doog

64. From a given file [Link], join the strings of each line of a file and write the result into
another file [Link], also display the contents of f1.

65. From a given file [Link], join the strings of each line of a file and write the result into
another file [Link], also display the contents of f1.

For example:

Tes Input Result


t

1 good morning goodmorning


welcome to welcometocla
class ss

66. Write a Pandas program to convert a dictionary to a Pandas series.

67. Write a Pandas program to convert a dictionary to a Pandas series.


For example:

Tes Input Result


t

2 {101: 'Smith', 102: 'John', 101 Smith


103:'Peter'} 102 John
103 Peter
dtype:
object
68. Write a Pandas program from given dictionary exam_data to get the first 3 rows of
DataFrame.
Sample DataFrame:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

69. Write a Pandas program from given dictionary exam_data to get the first 3 rows of
DataFrame.
Sample DataFrame:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

For example:

T Input Result
e
s
t
1 {'name': ['Anastasia', 'Dima', 'Katherine', 'James', name
'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', score attempts
'Jonas'], qualify
a Anastasia
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 12.5 1
8, 19], yes
b Dima
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 9.0 3
no
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', c Katherine
'yes', 'no', 'no', 'yes']} 16.5 2
yes

69. Write a Pandas program to replace all the NaN values with Zero's in a column of a
dataframe.
Original DataFrame:

Sample data:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0
2 2 Katherine yes 16.5
3 3 James no NaN
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no NaN
8 2 Kevin no 8.0
9 1 Jonas yes 19.0
New DataFrame replacing all NaN with 0:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0
2 2 Katherine yes 16.5
3 3 James no 0.0
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no 0.0
8 2 Kevin no 8.0
9 1 Jonas yes 19.0

70. Write a Pandas program to replace all the NaN values with Zero's in a column of a
dataframe.
Original DataFrame:

Sample data:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0
2 2 Katherine yes 16.5
3 3 James no NaN
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no NaN
8 2 Kevin no 8.0
9 1 Jonas yes 19.0
New DataFrame replacing all NaN with 0:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0
2 2 Katherine yes 16.5
3 3 James no 0.0
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no 0.0
8 2 Kevin no 8.0
9 1 Jonas yes 19.0

71. Write a Pandas program to drop a 2nd and 4th rows from a specified DataFrame.
Original DataFrame
col1 col2 col3
0147
1458
2369
3470
4581

72. Write a Pandas program to drop a 2nd and 4th rows from a specified DataFrame.
Original DataFrame
col1 col2 col3
0147
1458
2369
3470
4581

For example:

T Input Result
e
st
1 {'col1': [1, 4, 3, 4, 5], 'col2': [4, 5, 6, New DataFrame after
7, 8], 'col3': [7, 8, 9, 0, 1]} removing 2nd & 4th rows:
col1 col2 col3
0 1 4 7
1 4 5 8
3 4 7 0

73. Given an input file([Link]), find the longest word in the file.

74. Given an input file([Link]), find the longest word in the file.
For example:

Tes Input Result


t

1 Machine Learning ['Programming


Neural Networks ']
Python
Programming

75. Write a program to count the number of upper-case alphabets present in a text file
“[Link]”
For example:

Tes Input Result


t

1 Welcome Total no. of uppercase alphabets :


Hello World 11
Python Programming
Ease of programs
Predefined methods
Less lines of code
Has Many built in
packages
Popular now a days

76. Write a program to display all the lines in a file “[Link]” along with line/record
number.
77. Write a program to display all the lines in a file “[Link]” along with line/record
number.
For example:

Tes Input Result


t

1 Machine Learning 1 Machine Learning


Neural Networks
Python 2 Neural Networks
Programming
3 Python
Programming

78. A shopkeeper has 420 balls and 130 bats to pack in a day. She wants to pack them in
such a way that each set has the same number in a box, and they take up the least area of
the box. What is the number that can be placed in each set for this packing purpose?

[Link] an integer n, return a list containing


1 2 2 3 3 3 4 4 4 4 ... and finally n repeated n times.
You may assume n is 0 or greater
80. Python program to find the ASCII value of a character
81. Two rods are 22 m and 26 m long. The rods are to be cut into pieces of equal length.
Find the maximum length of each piece.
82. write a program to check whether given number is Fibonacci number or not?
83. Write a program of swapping of two numbers
84. Write a Python function that accepts a string and calculate the number of upper case
letters and lower case letters.
Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12
85. Write a Python program convert a given string list to a tuple
Original string: python3.0

Convert the said string to a tuple:


('p', 'y', 't', 'h', 'o', 'n', '3', '.', '0')
86. Write a Python program to compute element-wise sum of given tuples.
87. function to calculate factorial of a no and returns the values
88. function to print fibonacci series of given n
89. Given a list of 6 students names in L and a character,display the names of students
whose first letter is given character
['Arun','Swathi','Bharathi','Sai','Pallavi','Somu'],'S'
['Swathi', 'Sai', 'Somu']

90. Given a two-dimensional array of integers, return the average of the four corner
elements.
You may assume the array is at least 1x1.
Write a program with the function given below as example
def averageOfCorners(arr):
# Your code here…
pass
91. Write a program to read any Month Number in integer and display the number of days
for this month
92. Write a python program that returns a substring present between the first occurrence of
'*' and the last occurrence of the '*.'
93. Write program to Sort Tuples by Total digits
94. 12 boys and 15 girls are to march in a parade. The organizer wants them to march in
rows, with each row having the same number of children, and with each row composed of
children with the same gender. What is the largest number of children per row that satisfies
these constraints-Write a python program/instruction(s)
95. A rectangular floor measures 300 cm×195 cm 300 cm×195 cm. What is the largest
square tiles that can be used to cover the floor exactly-Write a python
program/instruction(s)
96. recursive function that returns product of given 2 nos
97. recursive function that returns product of given 2 nos
98. Write a program to eliminate duplicate values in the list
99. write a program to print prime numbers in a given range
def prime(a,b):

pass
100. Write a program using recursion to find the sum of series upto n
101. Write a python program that changes all the occurrences of the word "you" with "U" and
all the occurrences of the word "for" with "4".
If the sentence is not having either "you" or "for", input string has to be displayed as it is.
102. Write a python program to capitalize the first and last character of each word in a
string.
GITAM SCHOOL OF TECHNOLOGY,
HYDERABAD CAMPUS
(Declared as deemed-to-be-University u/s 3 of the UGC Act, 1956)
Department of Computer Science and Engineering

Minutes of Meeting

Date: 11-12-2023

A meeting was conducted on 11/12/2023 with Programming with Python course


faculty of I Yr B. Tech II Semester.

The following points were discussed.

1. II semester course work commenced from 12/12/2023 and class work


closure on 15/04/2024.
2. Mode of program execution through Google Colab.
3. For Assessment

Type of Exam Count Marks Weightage


Quizzes 5 5*5=25
Case Study 1 1*15= 15
Mids 3 3*10=30
End Exam 1 1*30=30

4. All Quizzes from each unit consist of - MCQS,Drag and drop questions,
Multi answer questions, code analysis.
5. Mid Examinations are planned to be conducted using Coding questions and
MCQS and Theory questions.
6. End examination is a combination of MCQS and programming questions.
7. Question bank must consist of programs and mcqs with difficulty level( Easy,
Moderate,Hard)
[Link]
ve_link
GITAM SCHOOL OF TECHNOLOGY,
HYDERABAD CAMPUS
(Declared as deemed-to-be-University u/s 3 of the UGC Act, 1956)
Department of Computer Science and Engineering

CIRCULAR

All the python course faculty are hereby informed to attend a


meeting at 6th floor conference hall on 5-2-2024 (2.30 P.M) to
discuss the following

Agenda of meeting
1. Syllabus coverage
2. Conduct of mid and quiz examinations
3. Question Bank Preparation
Minutes of Meeting

Date: 1-06-2022

A meeting was conducted on 5-2-2024 with Programming with Python course


faculty of I Yr B. Tech II Semester.

The faculty present in the meeting are


[Link] [Link]
[Link]. M. Kiran Sastry
3. Mr. Rajendra Prasad Babu
[Link]. Phani Sheetal

5. Dr. Santoshi

6. [Link] V

7. Ms Jyothi Bankapalli

The following points were discussed.

1. Quiz 1 is completed for all the sections.


2. Regarding the syllabus coverage all the faculty members are dealing with
module 2.
3. There is no reconduction of mid/quiz exams.
4. Quiz 2 and Mid1 Exams are planned in the conduct before 15-feb-2024.
5. Mid examinations are planned to conduct online through code runner by
giving 6 programming questions.(6*5=30 Marks).
6. Discussed to contribute questions in master repo for mid and quiz
examinations , same will be available in drive to avoid duplication.
[Link]
DIJN4?usp=drive_link
GITAM SCHOOL OF TECHNOLOGY,
HYDERABAD CAMPUS
(Declared as deemed-to-be-University u/s 3 of the UGC Act, 1956)
Department of Computer Science and Engineering

CIRCULAR

All the python course faculty are hereby informed to attend a


meeting at 6th floor conference hall on 8-4-2024 (4.00 P.M) to
discuss the following

Agenda of meeting
1. Syllabus coverage
2. Continuous evaluation marks
3. End semester exam question bank preparation
4. Update of marks in G- learn
Minutes of Meeting

Date: 1-06-2022

A meeting was conducted on 8-4-2024 with Programming with Python course


faculty of I Yr B. Tech II Semester.

The faculty present in the meeting are


[Link] [Link]
[Link]. M. Kiran Sastry
3. Mr. Rajendra Prasad Babu
[Link]. Phani Sheetal

5. Dr. Santoshi

6. [Link] V

7. Ms Jyothi Bankapalli

8. Mr jaipal

[Link] T Arun Singh

10. Mr Raj Mohammad

The following points were discussed.

1. Last working day for II Semester is 15-4-2024


2. Regarding the syllabus coverage all the faculty members are dealing with
module 5 and in few sections syllabus is completed .
3. End exam pattern (10 MCQS+ Programming questions)
4. Marks should upload by 15-4-2024 in G-learn.
Learners Report

Faculty Name: [Link]


Subject Name: Python programming
Subject Code: CSEN1021
Section: I
Year: 2023-24
Semester: II

The identification of slow learners and fast learners is based on their performance in the
assessments.
Slow learners are those scoring less than 50% of the total marks for a particular component, while
fast learners are those scoring more than 80% of the total marks.
This classification helps in providing targeted interventions to improve the performance of slow
learners and to further enhance the skills of fast learners.
Slow learners

Quiz 1 Quiz 2 Quiz 3 Quiz 4 Quiz 5 Mid 1 Mid 2 Mid 3 End


exam

20230025 20230032 20230032 20230032 20230021 20230025 2023003 20230021 20230027


91 18 18 09 17 18 439 17 66
20230030 20230033 20230033 20230032 20230030 20230025 20230030 20230030
71 02 52 18 71 91 53 18
20230032 20230033 20230033 20230033 20230032 20230027 20230033 20230030
15 42 62 02 18 66 97 37
20230032 20230033 20230034 20230033 20230032 20230030 20230034 20230030
78 67 39 19 25 18 20 45
20230033 20230033 20230033 20230032 20230030 20230034 20230031
91 74 42 96 45 39 81
20230034 20230033 20230033 20230033 20230030 20230032
22 95 52 02 53 12
20230034 20230034 20230033 20230033 20230030 20230032
39 04 81 52 59 15
20230067 20230034 20230034 20230033 20230030 20230032
87 17 04 69 71 18
20230067 20230034 20230033 20230031 20230032
87 33 86 81 78
20230034 20230033 20230031 20230032
39 95 96 81
20230034 20230032 20230032
04 09 93
20230034 20230032 20230032
12 12 96
20230034 20230032 20230033
20 15 02
20230034 20230032 20230033
38 18 19
20230034 20230032 20230033
39 78 26
20230067 20230032 20230033
87 81 52
20230032 20230033
85 62
20230032 20230033
88 80
20230032 20230033
93 81
20230032 20230033
96 94
20230033 20230034
01 04
20230033 20230034
02 39
20230033
16
20230033
19
20230033
26
20230033
29
20230033
42
20230033
52
20230033
62
20230033
67
20230033
68
20230033
69
20230033
74
20230033
80
20230033
81
20230033
86
20230033
94
20230033
95
20230033
97
20230034
04
20230034
12
20230034
17
20230034
22
20230034
25
20230034
33
20230034
38
20230034
39
20230034
54
20230063
59
20230067
87

Review and Improvement Suggestions

Improvement Area Suggestions


Slow learners Provide additional practice sessions and personalized guidance.
Others Encourage participation in group activities and peer learning.
Learners Report

Fast learners Offer advanced topics and research opportunities.

Fast Learners

You might also like