Python Course File
Python Course File
HYDERABAD CAMPUS
(Declared as deemed-to-be-University u/s 3 of the UGC Act, 1956)
Department of Computer Science and Engineering
[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
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
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
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]
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.
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
APPROVED IN:
BOS : September 6, 2021 ACADEMIC COUNCIL: 21st AC(September 17, 2021)
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
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
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
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
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
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
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
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
14 Dr. B. R. Ambedkar Jayanthi 03 Summer Term - Registration end 21 International Yoga Day
16 Even Semester-Submission of continuous evaluation 10 Basava Jayanthi (BLR) 28 Summer Term end
marks
JULY 2024
07 Bonalu (HYD)
15 Last date for Payment of tuition fee for ODD semester
without fine
-By Registrar
Section :- T,I,M
The strip() method removes any whitespace from the beginning or the end
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.
• Constant Description
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
Definite condition :
Ex: range of number s, list, dictionary, file…..etc
Course name:
❖ They can be enclosed in single quotes (‘…...') or double quotes (“…...") with the
same result.
❖ 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
• 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‘]
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](key=None, reverse=False) : Sort the items of the list in place (the arguments
can be used for sort customization, )
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
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.
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.
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.
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.
>>> 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‘
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.
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
SQLite3:
CRUD operations (Create, Read, Update, and Delete) to manage data stored in a
database.
Matplotlib :
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}
1 [Link].t banan
xt a
3
apple
grape
s
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:
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:
12. Given an input file([Link]), find the longest word in the file.
For example:
13. Write a program to count the number of upper-case alphabets present in a text file
“[Link]”
For example:
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]))
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
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
25. Write python code to merge two dictionaries into a single one.
For example:
Te Input Result
st
Input Result
(2, 4, 8, 8, 3, 2, 27648
9)
Input Result
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
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
Answer:(penalty regime: 0 %)
36. Read the given csv file and answer the following questions
File name:
C_PROGRAMMING_SET_1.csv
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
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)
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
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}
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
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}
my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
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]())
s1=input()
s2=input()
dict1=eval(s1)
dict2=eval(s2)
[Link](dict2)
print(dict1)
f=open("[Link]","r")
l=[Link]()
print(len(l))
Moderate(total 15)
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()
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'}
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
Sample solution:
import pandas as pd
import numpy as np
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
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)
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.
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.
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:
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
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
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
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
Student(Name,Id,Section,Branch,Marks)
Student(Name,Id,Section,Branch,Marks)
Note: Assume that above student table is available with the data.
Student(Name,Id,Section,Branch,Marks)
10. Write a SQLite program to find sum, average, minimum mark and maximum
mark of the class.
Student(Name,Id,Section,Branch,Marks)
Regular Expressions
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
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.
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
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
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}
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}
my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
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]())
s1=input()
s2=input()
dict1=eval(s1)
dict2=eval(s2)
[Link](dict2)
print(dict1)
f=open("[Link]","r")
l=[Link]()
print(len(l))
Moderate(total 15)
Visakhapatnam City
Tanali Town
Mumbai City
Kodavatikallu Village
Maavooru Village
Anantapuram Town
your task is to form a dictionary which looks like this
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()
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'}
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
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
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
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)
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.
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.
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:
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
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
8. Write a Python program to Calculate total sale data for last year for each product and
show it using a Pie chart
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)
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.
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'
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:
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
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:
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:
75. Write a program to count the number of upper-case alphabets present in a text file
“[Link]”
For example:
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:
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?
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
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
Agenda of meeting
1. Syllabus coverage
2. Conduct of mid and quiz examinations
3. Question Bank Preparation
Minutes of Meeting
Date: 1-06-2022
5. Dr. Santoshi
6. [Link] V
7. Ms Jyothi Bankapalli
CIRCULAR
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
5. Dr. Santoshi
6. [Link] V
7. Ms Jyothi Bankapalli
8. Mr jaipal
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
Fast Learners