GE3171 – PROBLEM SOLVING AND PYTHON PROGRAMMING LAB MANUAL
GE3171 – PROBLEM SOLVING AND PYTHON PROGRAMMING LAB MANUAL
OF
COMPUTER SCIENCE & ENGINEERING
LAB MANUAL
GE3171
PROBLEM SOLVING AND PYTHON PROGRAMMING
LABORATORY
M1 To excel in teaching and learning, research and innovation by promoting the principles
of scientific analysis and creative thinking
To equip students with values, ethics and life skills needed to enrich their lives and
M3
enable them to meaningfully contribute to the progress of society
M4 To prepare students for higher studies and lifelong learning, enrich them with the
practical and entrepreneurial skills necessary to excel as future professionals and
contribute to Nation’s economy
Program Outcomes (POs)
Engineering knowledge: Apply the knowledge of mathematics, science, engineering
PO1 fundamentals, and an engineering specialization to the solution of complex engineering
problems.
Problem analysis: Identify, formulate, review research literature, and analyze complex
PO2 engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess
PO6 societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
Vision of Department
To emerge as a globally prominent department, developing ethical computer professionals,
innovators and entrepreneurs with academic excellence through quality education and research .
Mission of Department
To create computer professionals with an ability to identify and formulate the
M1
engineering problems and also to provide innovative solutions through effective teaching
learning process.
M3 To produce engineers with good professional skills, ethical values and life skills for the
betterment of the society.
An ability to understand the core concepts of computer science and engineering and to enrich
PSO1 problem solving skills to analyze, design and implement software and hardware based
systems of varying complexity.
PSO2 To interpret real-time problems with analytical skills and to arrive at cost effective and
optimal solution using advanced tools and techniques.
An understanding of social awareness and professional ethics with practical proficiency in the
PSO3 broad area of programming concepts by lifelong learning to inculcate employment and
entrepreneurship skills.
COURSE OUTCOMES
CO1: Develop algorithmic solutions to simple computational problems
CO2: Develop and execute simple Python programs.
CO3: Implement programs in Python using conditionals and loops for solving problems.
CO4: Deploy functions to decompose a Python program.
CO5: Process compound data using Python data structures.
CO6: Utilize Python packages in developing software applications.
LIST OF EXERCISES
1. Identification and solving of simple real life or scientific or technical problems, and developing
flow charts for the same. (Electricity Billing, Retail shop billing, Sin series, weight of a
motorbike, Weight of a steel bar, compute Electrical Current in Three Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns,
pyramid pattern)
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
7. Implementing programs using Strings. (reverse, palindrome, character count, replacing
characters)
8. Implementing programs using written modules and Python Standard Libraries (pandas, numpy.
Matplotlib, scipy)
9. Implementing real-time/technical applications using File handling. (copy from one file to another,
word count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by zero error,
voter’s age validity, student mark range validation)
12. Developing a game activity using Pygame like bouncing ball, car race etc.
GE3171 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
INDEX
11 Exploring Pygame
Date :
3. Flowcharts:
A. Electricity Billing
Algorithm:
Start
Get
the
unit U
value
Yes 𝐼𝑓 𝑈 ≤
No
100
𝐼𝑓 𝑈
No
Bill = 0 > 100
≤ 200
Yes
𝐼𝑓 𝑈
Bill = U * 2 > 200
Yes
Bill = U * 3
Print
bill
Stop
B. Retail shop billing
Algorithm:
Step 1: Start the algorithm
Step 2: Enter option(i) as integer value
Step 3: If option(i) is not 0,
i)Get the item name(it),quantity(q) and its price(p) as input.
ii)Calculate the bill by it*q*p.
If the option(i) is equal to 0, come out of the loop
Step 4: Print the bill values.
Step 5: Stop the algorithm.
Start
𝐵=0
Enter i
No 𝐵 = 𝐵 + (𝑖𝑡 ∗ 𝑞 ∗ 𝑝)
Print B
Stop
C. Sine Series:
Algorithm:
Get x and i
fact = 1; 𝑖 = 1
fact = fact ∗ k
x = x + pow(x, i)/fact
i=i+2
Display x
𝑆𝑡𝑜𝑝
D: weight of a motorbike
Algorithm:
Step 1: Start the algorithm
Step 3: Get the types of motorcycle M
Step 4: Based on the type M, choose the weight as
If M=chopper, W= 315 kg
If M=Cruiser, W=250 kg
If M=Scooter, W=115 kg
If M=Mopped, W=80 kg
Else print as cannot find the weight
Step 5: Print the weight
Step 6: Stop the algorithm.
Start
𝑆𝑤𝑖𝑡𝑐ℎ 𝑀
𝐶𝑎𝑠𝑒 Yes
𝑊 = 315 𝑘𝑔
= 𝐶ℎ𝑜𝑝𝑝𝑒𝑟
No
𝐶𝑎𝑠𝑒 Yes
𝑊 = 250 𝑘𝑔
= 𝐶𝑟𝑢𝑖𝑠𝑒𝑟
No
𝐶𝑎𝑠𝑒 Yes
𝑊 = 115 𝑘𝑔
= 𝑆𝑐𝑜𝑜𝑡𝑒𝑟
No
𝐶𝑎𝑠𝑒 Yes
𝑊 = 80 𝑘𝑔
= 𝑀𝑜𝑝𝑝𝑒𝑑
No
Weight (W)
cannot calculated
Print w
𝑆𝑡𝑜𝑝
E. Weight of a steel bar
Algorithm:
Step 1: Start the algorithm
Step 2: Get the diameter d of a steel bar.
Step 3: If d>= 8 mm and <= 20 mm then
Calculate the W as (d*d)/162
Print W
Else
Print as not available
Step 4: Stop the algorithm.
Start
Get d
Yes
𝐼𝑓 𝑑 ≥ 8 𝑚𝑚
≤ 20 𝑚𝑚
𝑊 = (𝑑 ∗ 𝑑 )/162
No
Print not
available
Ghhjjkj Print w
𝑆𝑡𝑜𝑝
F. Compute Electrical Current in Three Phase AC Circuit
Algorithm:
Step 1: Start the algorithm
Step 2: Get the power factor Pf, Power P and Voltage V.
Step 3: Calculate the current I as 𝑃/√3 ∗ 𝑉 ∗ 𝑃𝑓
Step 4: Print the current I.
Step 5: Stop the algorithm
Start
Get P,
Pf, V
𝐼 = 𝑃/√3 ∗ 𝑉 ∗ 𝑃𝑓
Print 𝐼
𝑆𝑡𝑜𝑝
4. Result
Thus the flowcharts for Electricity Billing, Retail shop billing, Sine series, weight of a
motorbike, Weight of a steel bar, compute Electrical Current in Three Phase AC Circuit are
drawn.
5. Viva voice
Date :
3. Problem Analysis:
I. Using simple statement exchange the values of two variables should be
implemented by getting two integer values x,y as input and print their values after
swapping them.
II. Using List, circulate the values of n variables by getting a value is to be
circulated,list_1 and position from where it should circulate, n as inputs.
III. Using simple statement and expressions, distance between two points are to be
implemented. It gets two floating point values (x1,y1) and (x2,y2) and by
applying the distance formula ( (x2 - x1)2 + (y2 - y1)2 )½ the distance between them
is calculated and displayed.
4. A. Expected Input:
I. enter x value : 50
enter y value : 10
II. enter n value :1
III. enter x1 : 5
enter y1 : 4
enter x2 : 6
enter y2 : 3
B. Expected Output :
I. After swapping value of x = 10
After swapping value of y = 50
II. Rotating [10, 20, 30, 40, 50] by 1 position is [50, 10, 20, 30, 40]
III.Distance between points (5.0, 4.0) and (6.0, 3.0) is 1.4142135623730951
5. Algorithm:
I.
Step 1: Start the program
Step 2 : Get the input for two variables x, y.
Step 3 : Have a third variable temp and first assign x to temp; then assign y value to x
and
assign temp value to x
Step 4: Print the swapped value of x and y.
Step 5: Stop the program.
II.
Step 1 : Start the program
Step 2 : Initialize numbers using list.
Step 3 : Also get a value n for rotation.
Step 4 : Obtain the numbers available from the nth position, the numbers till n position
and append the both values.
Step 5: Display the result.
Step 6: Stop the program.
III.
Step 1: Start the program.
Step 2: Get two points, namely(x1,y1) and (x2,y2).
Step 3: Calculate the distance between two points by using ( (x2 - x1)2 + (y2 - y1)2 )½
Step 4: Display the resultant distance value.
Step 5: Stop the program
6. Coding:
iii) Write a python program to calculate the distance between two points.
#Python program to find distance between two points
# point a
x1 = float(input(“enter x1 : ”))
y1 = float(input(“enter y1 : ”))
# point b
x2 = float(input(“enter x2 : ”))
y2 = float(input(“enter y2 : ”))
7. Test cases:
Input Output
I enter x value : 45 After swapping value of x = 34
enter y value : 34 After swapping value of y = 45
enter x value : 4.5 ValueError: invalid literal for int() with base 10: '4.5'
enter x value : g NameError: name 'g' is not defined
enter x value : '33' ValueError: invalid literal for int() with base 10: "'33'"
II enter n value :1 Rotating [1, 2, 3, 4, 5, 6] by 1 position is [6, 1, 2, 3, 4, 5]
enter n value :2 Rotating [1, 2, 3, 4, 5, 6] by 2 position is [5, 6, 1, 2, 3, 4]
enter n value : 3 Rotating [1, 2, 3, 4, 5, 6] by 3 position is [4, 5, 6, 1, 2, 3]
enter n value : 2 Rotating [1.0, 2.6, 3.5, 4.8, 5.9, 6.3] by 2 position is [5.9,
6.3, 1.0, 2.6, 3.5, 4.8]
enter n value : 2 Rotating ['a', 'b', 'c', 'd', 'e'] by 2 position is ['d', 'e', 'a', 'b',
'c']
enter n value : 3 Rotating ['champa', 'lotus', 'lily', 'rose', 'jasmine'] by 3
position is ['lily', 'rose', 'jasmine', 'champa', 'lotus']
III enter x1 : 2 Distance between points (2.0, 3.0) and (5.0, 7.0) is 5.0
enter y1 : 3
enter x2 : 5
enter y2 : 7
enter x1 : a name 'a' is not defined
enter x1 : 'a' ValueError: could not convert string to float: "'a'"
8. Output:
i)enter x value : 77
enter y value : 105
After swapping value of x = 105
After swapping value of y = 77
ii)enter n value : 4
Rotating [45, 76, 34, 65, 34, 90, 23] by 4 position is [65, 34, 90, 23, 45, 76, 34]
iii)enter x1 : 56
enter y1 : 4
enter x2 : 51
enter y2 : 4
Distance between points (56.0, 4.0) and (51.0, 4.0) is 5.0
9. Result
Thus the python program to swap the values of two numbers, circulate the values of
n variables, distance between two points using simple statements and expressions are
executed successfully.
B. Define algorithm.
An algorithm is a process or set of rules to be followed in calculations or other
problem-solving operations, especially by a computer.
D. What is a string?
A string is a data type used in programming to represent text rather than numbers.
It is comprised of a set of characters that can also contain spaces and numbers. For example,
the word "hamburger" and the phrase "I ate 3 hamburgers" are both strings.
Date :
2. Expected Learning Outcomes: Train the students to understand the basics of various
conditional and looping statements
3. Problem Analysis:
I. Identify the appropriate looping statement to implement the number series which
gets the N value from the user and prints sum of first N value and squares of first
N values.
II. Using appropriate conditional and looping statement implement a number patterns
which gets a two number’s X and Y. X and Y should be an positive number and
X should be greater than Y (X>Y). Keep decrementing X from Y until you
encounter 0. Once it reaches 0 keep incrementing X by Y until the value reaches
X or above
III. Using loops construct a pyramid. Generate the pyramid with an alphabet patterns
or star patterns. Get the number of rows R in the pyramid from the user.
4. A. Expected Input:
B. Expected Output:
*
**
***
****
*****
******
*******
5. Algorithm:
I.
Step 1: Get the input from the user and store the value in n
Step 2: Initialize two variables to store the square and sum
Step 3: Initialize i=1
Step 4: Repeat Step 5 through Step 7 until i <= n
Step 5: Calculate Square = Square + (i*i)
Step 6: Calculate Sum = Sum + i
Step 7: Increment i by 1
Step 8 : Display Square and Sum
Step 9: Stop
II.
Step 1: Get the X and Y values as input from the user
Step 2: Initialize two variables to store the square and sum
Step 3: Initialize i=1
Step 4: Repeat Step 5 through Step 12 until i <= X*2+Y
Step 5: if X-i >= 0 goto Step 6 else goto Step 8
Step 6: Calculate a = X-i
Step 7 : Display a
Step 8: if X-i < 0 goto Step 9 else goto Step 12
Step 9: Calculate a = X-i
Step 10: Calculate a = a + a*-2
Step 11: Display a
Step 12: Increment i by 1
Step 13: Stop
III.
Step 1: Get the number of rows R from the user
Step 2: Initialize a temporary variable K to count on number of spaces
Step 3: Initialize i=1. Create an outer loop to handle number of rows.
Step 4: Repeat Step 5 through Step 8 until i <=n
Step 5: Initialize j=1. Create inner loop to handle number spaces.
Step 6: Repeat Step 7 through Step 8 until j <=n
Step 7: Display a space
Step 8: Decrement K by 1 after each loop
Step 9: Initialize j=1. Create inner loop to handle number of columns.
Step 10: Repeat Step 11 through Step 13 until j <=n
Step 11: Display ‘*’
Step 12: Increment i
Step 13: Stop
6. Coding:
I. Write a program to print Square series and addition series. Display square
of N natural numbers and sum of N natural numbers
Square = 0
Sum = 0
print('The Square of the given number',N,'is: ')
for i in range(1, N+1) :
Square = Square + (i * i)
print(Square,end=' ')
print('\n',end=' ')
print('The Sum of the given number',N,'is: ')
for i in range(1, N+1) :
Sum = Sum + i
print(Sum,end=' ')
Input Output
I Please enter the value of N:10 The Square of the given number 10
is:
1 5 14 30 55 91 140 204 285 385
The Sum of the given number 10 is:
1 3 6 10 15 21 28 36 45 55
Please enter the value of N:-2 The Square of the given number -2
is:
8. Output :
iii.
*
**
***
****
*****
******
*******
9. Result
Number series, Number pattern and pyramid pattern were successfully implemented
through conditional if statement, nested if statement, looping statement through for loop
and nested for loop
10. Viva Questions
A. Which operator is used to check the equality of the two operands?
The equal-to operator ( == ) returns true if both operands have the same value;
otherwise, it returns false .
The colon (:) is significant and required. It separates the header of the compound
statement from the body.
The line after the colon must be indented. It is standard in Python to use four
spaces for indenting.
All lines indented the same amount after the colon will be executed whenever the
BOOLEAN_EXPRESSION is true.
Yes. One of the distinctive features of Python is its use of indentation to highlighting
the blocks of code. Whitespace is used for indentation in Python. All statements with
the same distance to the right belong to the same block of code.
[0,1,2,3,4,5,6,7,8,9]
Ex.No: 4 Implementing real-time/technical applications using Lists,
Tuples.
Date :
1. Problem Statement: Write a python program to create and perform the operations of list
and tuple for the items present in a library
2. Expected Learning Outcomes: Train the students to understand the operations of list
and tuple
3. Problem Analysis:
I. Using list, implement operations of addition and deletion of items in library, and
differentiate the operations which can be performed by tuple.
II. Perform the slicing operations for the materials required for construction using list
and tuple
4. A. Expected Input:
I. Enter the items in the library separated by space: Books Journals Articles Novels
II. Enter the Material List required for construction separated by space: mSand Steel
Stones PVC Plaster Putty
III. Enter the Material Tuple required for construction separated by space:Cement
Sand Bars Bricks Paint Wood Tiles
B. Expected Output:
I.
Enter the items in the library separated by space: Books Journals Articles Novels
List of items in the library: ['Books', 'Journals', 'Articles', 'Novels']
List of items in the library after appending new item: ['Books', 'Journals', 'Articles',
'Novels', 'Newspaper']
List of items in the library after adding new item at 3rd index: ['Books', 'Journals',
'Articles', 'eAssets', 'Novels', 'Newspaper']
List of items in the library after removing an item: ['Books', 'Journals', 'Articles', 'Novels',
'Newspaper']
List of items in the library after removing an item at 2nd index: ['Books', 'Journals',
'Novels', 'Newspaper']
The list library is converted to tuple library now
The items in the tuple library is ('Books', 'Journals', 'Novels', 'Newspaper')
Length of the tuple library is: 4
Yes, 'Newspaper' is an item in the library tuple
II.
Actual string: Common Materials required for construction
The substring after slice (7, 25): Materials required
Original List: ['mSand', 'Steel', 'Stones', 'PVC', 'Plaster', 'Putty']
Sliced List with slice(1, 5, 1): ['Steel', 'Stones', 'PVC', 'Plaster']
The List after negative values for slice: ['Putty', 'Plaster', 'PVC']
Sliced List with [2:6:1: ['Stones', 'PVC', 'Plaster', 'Putty']
Sliced List with [1::]: ['Steel', 'Stones', 'PVC', 'Plaster', 'Putty']
Original Tuple: ['Cement', 'Sand', 'Bars', 'Bricks', 'Paint', 'Wood', 'Tiles']
The tuple after slice: ['Cement', 'Sand', 'Bars', 'Bricks']
Sliced Tuple with [:]: ['Cement', 'Sand', 'Bars', 'Bricks', 'Paint', 'Wood', 'Tiles']
Sliced Tuple with [::-1] = ['Tiles', 'Wood', 'Paint', 'Bricks', 'Bars', 'Sand', 'Cement']
Sliced Tuple with [-1:-4:-1] = ['Tiles', 'Wood', 'Paint']
5. Algorithm:
I.
II.
I.
Write a python program to create and perform the operations of list and
tuple for the items present in a library
II.
Write a python program to perform the slicing operations of list and tuple
for the materials required for construction
7. Test case :
Input Output
I Enter the items in the library separated by Enter the items in the library separated by space:
space: Books Journals Articles Novels Books Journals Articles Novels
List of items in the library: ['Books', 'Journals',
'Articles', 'Novels']
List of items in the library after appending new item:
['Books', 'Journals', 'Articles', 'Novels', 'Newspaper']
List of items in the library after adding new item at
3rd index: ['Books', 'Journals', 'Articles', 'eAssets',
'Novels', 'Newspaper']
List of items in the library after removing an item:
['Books', 'Journals', 'Articles', 'Novels', 'Newspaper']
List of items in the library after removing an item at
2nd index: ['Books', 'Journals', 'Novels', 'Newspaper']
The list library is converted to tuple library now
The items in the tuple library is ('Books', 'Journals',
'Novels', 'Newspaper')
Length of the tuple library is: 4
Enter the items in the library separated by IndexError: list assignment index out of range
space: Books,Journals,Articles,Novels
Enter the items in the library separated by Enter the items in the library separated by space: 1 2 3
space: 1 2 3 4 4
List of items in the library: ['1', '2', '3', '4']
List of items in the library after appending new item:
['1', '2', '3', '4', 'Newspaper']
List of items in the library after adding new item at 3rd
index: ['1', '2', '3', 'eAssets', '4', 'Newspaper']
List of items in the library after removing an item: ['1',
'2', '3', '4', 'Newspaper']
List of items in the library after removing an item at
2nd index: ['1', '2', '4', 'Newspaper']
The list library is converted to tuple library now
The items in the tuple library is ('1', '2', '4',
'Newspaper')
Length of the tuple library is: 4
Yes, 'Newspaper' is an item in the library tuple
II Enter the Material List required for Actual string: Common Materials required for
construction separated by space: mSand Steel construction
Stones PVC Plaster Putty The substring after slice (7, 25): Materials required
Enter the Material Tuple required for Original List: ['mSand', 'Steel', 'Stones', 'PVC',
construction separated by space:Cement 'Plaster', 'Putty']
Sand Bars Bricks Paint Wood Tiles Sliced List with slice(1, 5, 1): ['Steel', 'Stones', 'PVC',
'Plaster']
The List after negative values for slice: ['Putty',
'Plaster', 'PVC']
Sliced List with [2:6:1: ['Stones', 'PVC', 'Plaster',
'Putty']
Sliced List with [1::]: ['Steel', 'Stones', 'PVC', 'Plaster',
'Putty']
Original Tuple: ['Cement', 'Sand', 'Bars', 'Bricks',
'Paint', 'Wood', 'Tiles']
The tuple after slice: ['Cement', 'Sand', 'Bars', 'Bricks']
Sliced Tuple with [:]: ['Cement', 'Sand', 'Bars', 'Bricks',
'Paint', 'Wood', 'Tiles']
Sliced Tuple with [::-1] = ['Tiles', 'Wood', 'Paint',
'Bricks', 'Bars', 'Sand', 'Cement']
Sliced Tuple with [-1:-4:-1] = ['Tiles', 'Wood', 'Paint']
Enter the Material List required for Actual string: Common Materials required for
construction separated by space: 1 2 3 4 5 6 construction
Enter the Material Tuple required for The substring after slice (7, 25): Materials required
construction separated by space:1 2 3 4 5 6 Original List: ['1', '2', '3', '4', '5', '6']
Sliced List with slice(1, 5, 1): ['2', '3', '4', '5']
The List after negative values for slice: ['6', '5', '4']
Sliced List with [2:6:1: ['3', '4', '5', '6']
Sliced List with [1::]: ['2', '3', '4', '5', '6']
Original Tuple: ['1', '2', '3', '4', '5', '6']
The tuple after slice: ['1', '2', '3', '4']
Sliced Tuple with [:]: ['1', '2', '3', '4', '5', '6']
Sliced Tuple with [::-1] = ['6', '5', '4', '3', '2', '1']
Sliced Tuple with [-1:-4:-1] = ['6', '5', '4']
8. Output :
I.
Enter the items in the library separated by space: Books Journals Articles Novels
List of items in the library: ['Books', 'Journals', 'Articles', 'Novels']
List of items in the library after appending new item: ['Books', 'Journals', 'Articles',
'Novels', 'Newspaper']
List of items in the library after adding new item at 3rd index: ['Books', 'Journals',
'Articles', 'eAssets', 'Novels', 'Newspaper']
List of items in the library after removing an item: ['Books', 'Journals', 'Articles', 'Novels',
'Newspaper']
List of items in the library after removing an item at 2nd index: ['Books', 'Journals',
'Novels', 'Newspaper']
The list library is converted to tuple library now
The items in the tuple library is ('Books', 'Journals', 'Novels', 'Newspaper')
Length of the tuple library is: 4
Yes, 'Newspaper' is an item in the library tuple
II.
Actual string: Common Materials required for construction
The substring after slice (7, 25): Materials required
Original List: ['mSand', 'Steel', 'Stones', 'PVC', 'Plaster', 'Putty']
Sliced List with slice(1, 5, 1): ['Steel', 'Stones', 'PVC', 'Plaster']
The List after negative values for slice: ['Putty', 'Plaster', 'PVC']
Sliced List with [2:6:1: ['Stones', 'PVC', 'Plaster', 'Putty']
Sliced List with [1::]: ['Steel', 'Stones', 'PVC', 'Plaster', 'Putty']
Original Tuple: ['Cement', 'Sand', 'Bars', 'Bricks', 'Paint', 'Wood', 'Tiles']
The tuple after slice: ['Cement', 'Sand', 'Bars', 'Bricks']
Sliced Tuple with [:]: ['Cement', 'Sand', 'Bars', 'Bricks', 'Paint', 'Wood', 'Tiles']
Sliced Tuple with [::-1] = ['Tiles', 'Wood', 'Paint', 'Bricks', 'Bars', 'Sand', 'Cement']
Sliced Tuple with [-1:-4:-1] = ['Tiles', 'Wood', 'Paint']
9. Result
The operations of list and tuple were successfully implemented for the items in library.
We can’t add elements to a tuple. There’s no append() or extend() method for tuples.
We can’t remove elements from a tuple. Tuples have no remove() or pop() method.
We can find elements in a tuple since this doesn’t change the tuple.
We can also use the in operator to check if an element exists in the tuple.
To concatenate lists, we use the + operator. This will give us a new list that is the
concatenation of our two lists without modifying the original ones.
A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values.
By using the negative value, we may reverse the order of sequence for slicing. If we
want to count from the last item and return complete list, tuple etc., then use the -1
value.
Ex.No: 5 Implementing real-time/technical applications using Sets,
Dictionaries.
Date :
1. Problem Statement: Write python programs to perform the various operations using Sets
and Dictionaries.
2. Expected Learning Outcomes: Train the students to understand the operations available
for Sets and Dictionaries in python using real-time examples
3. Problem Analysis:
I. Use the possible methods to perform the create, access, add, length, remove,
clear and delete operations of Language sets in python.
II. Using dictionaries perform the create, access, change, add, remove, clear and
delete operations of automobile components in python.
III. Perform the conditional check, iteration, length, and sort operations for the
dictionary with the elements of civil structure.
4. A. Expected Input:
I.
Enter the Languages separated by space: English French German
II.
Enter input pair for Key 'Chasis' : Hatchback
Enter input pair for Key 'Engine' : VCylinder
Enter input pair for Key 'Capacity' : 1000cc
Enter input pair for Key 'Variant' : Petrol
III.
Enter number of 'Pillars': 100
Enter number of 'Floors': 5
Enter number of 'Windows': 50
B. Expected Output:
I.
{'French', 'German', 'English'}
True
{'French', 'Chinese', 'German', 'English'}
{'French', 'Malayalam', 'Tamil', 'Telugu', 'German', 'Chinese', 'English'}
7
{'French', 'Malayalam', 'Tamil', 'Telugu', 'German', 'English'}
{'Malayalam', 'Tamil', 'Telugu', 'German', 'English'}
Malayalam
{'Tamil', 'Telugu', 'German', 'English'}
set()
Traceback (most recent call last):
File "<string>", line 31, in <module>
NameError: name 'Language' is not defined
II.
{'Chasis': 'Hatchback', 'Engine': 'VCylinder', 'Capacity': '1000cc', 'Variant': 'Petrol'}
VCylinder
VCylinder
{'Chasis': 'Hatchback', 'Engine': 'VCylinder', 'Capacity': '1000cc', 'Variant': 'Petrol',
'Cost': '75000'}
{'Chasis': 'Hatchback', 'Engine': 'TwinCylinder', 'Capacity': '1000cc', 'Variant':
'Petrol', 'Cost': '75000'}
75000
{'Chasis': 'Hatchback', 'Engine': 'TwinCylinder', 'Capacity': '1000cc', 'Variant':
'Petrol'}
('Variant', 'Petrol')
{'Chasis': 'Hatchback', 'Engine': 'TwinCylinder', 'Capacity': '1000cc'}
{'Chasis': 'Hatchback', 'Capacity': '1000cc'}
{}
Traceback (most recent call last):
File "<string>", line 35, in <module>
NameError: name 'automobile' is not defined
III.
{'Pillars': '100', 'Floors': '5', 'Windows': '50'}
Contents of the Dictionary = {'Pillars': '100', 'Floors': '5', 'Windows': '50'}
Checking if Pillars is a key in dictionary = True
Checking if Walls is not a key in dictionary = True
Cannot check with pair value 50 in dictionary (True - pair can be checked, False -
pair cannot be checked = False
Pair values in the dictionary =
100
5
50
Length of the dictionary = 3
Sort the keys of the dictionary in alphabetical order = ['Floors', 'Pillars', 'Windows']
5. Algorithm:
I.
Step 1: Create a language set with user inputs as English, French and German
Step 2: Check/Access whether German is in the set.
Step 3: Add Chinese to the set
Step 4: Update the set with Tamil, Telugu and Malayalam
Step 5: Print the length of the set
Step 6: Remove Chinese from the set
Step 7: Discard French from the set
Step 8: Use Pop to do random removal of the set
Step 9: Clear the set
Step 10: Delete the set
Step 11: Display the error on printing deleted set
Step 12: Stop
II.
Step 1: Create an automobile component dictionary pair, key: value as Type: Bike,
Engine: 2Stroke, Capacity: 100cc}
Step 2: Access the value for the Key "Engine"
Step 3: Access the value for the Key "Engine" using get
Step 4: Add a new key: value as Cost: 75000
Step 5: Update the pair for the key "Engine" as "4Stroke"
Step 6: Remove the particular "Cost" key using pop
Step 7: Remove an arbitrary key using popitem
Step 8: Delete the particular "Engine" key
Step 9: Clear the dictionary
Step 10: Delete the dictionary
Step 11: Display the error on printing deleted dictionary
Step 12: Stop
III.
Step 1: Create an civil elements dictionary pair, key: value as Pillars: 100, Floors: 5,
Windows: 50, Doors: 60
Step 2: List the contents of the dictionary
Step 3: Check if "Pillars" is an element key
Step 4: Check if "Walls" is not an element key
Step 5: Check if pair value can be checked in dictionary
Step 6: List the pair values using for loop iteration
Step 7: Display the length of the dictionary
Step 8: Sort the element keys in alphabetical order
Step 9: Stop
6. Coding:
I. Write a python program to perform the create, access, add, length, remove, clear and
delete operations of Language sets.
#Step 1
list = list(map(str, input("Enter the Languages separated by space: ").split()))
Language = set(list)
print(Language)
#Step 2
print("German" in Language)
#Step 3
Language.add("Chinese")
print(Language)
#Step 4
Language.update(["Tamil", "Telugu", "Malayalam"])
print(Language)
#Step 5
print(len(Language))
#Step 6
Language.remove("Chinese")
print(Language)
#Step 7
Language.discard("French")
print(Language)
#Step 8
x = Language.pop()
print(x)
print(Language)
#Step 9
Language.clear()
print(Language)
#Step 10
del Language
#Step 11
print(Language)
II. Write a python program to perform the create, access, change, add, length, remove,
clear and delete operations of automobile component dictionary.
#Step 1
v1=input("Enter input pair for Key 'Chasis' : ")
v2=input("Enter input pair for Key 'Engine' : ")
v3=input("Enter input pair for Key 'Capacity' : ")
v4=input("Enter input pair for Key 'Variant' : ")
automobile={"Chasis":v1, "Engine":v2, "Capacity":v3, "Variant":v4}
print(automobile)
#Step 2
x = automobile["Engine"]
print(x)
#Step 3
x = automobile.get("Engine")
print(x)
#Step 4
automobile['Cost'] = '75000'
print(automobile)
#Step 5
automobile['Engine'] = "TwinCylinder"
print(automobile)
#Step 6
print(automobile.pop("Cost"))
print(automobile)
#Step 7
print(automobile.popitem())
print(automobile)
#Step 8
del automobile["Engine"]
print(automobile)
#Step 9
automobile.clear()
print(automobile)
#Step 10
del automobile
#Step 11
print(automobile)
III. Write a python program to perform the conditional check, iteration, length, and sort
operations for the dictionary with the elements of civil structure.
v1=input("Enter number of 'Pillars': ")
v2=input("Enter number of 'Floors': ")
v3=input("Enter number of 'Windows': ")
civilelements={"Pillars":v1, "Floors":v2, "Windows":v3}
print(civilelements)
print("Contents of the Dictionary =", civilelements)
print("Checking if Pillars is a key in dictionary =", "Pillars" in civilelements)
print("Checking if Walls is not a key in dictionary =", "Walls" not in civilelements)
print("Cannot check with pair value 50 in dictionary (True - pair can be checked, False
- pair cannot be checked =", "50" in civilelements)
print("Pair values in the dictionary =")
for i in civilelements:
print(civilelements[i])
print("Length of the dictionary =", len(civilelements))
print("Sort the keys of the dictionary in alphabetical order =", sorted(civilelements))
7. Test case:
Input Output
I. Enter the {'French', 'German', 'English'}
Languages True
separated {'French', 'Chinese', 'German', 'English'}
by space: {'French', 'Malayalam', 'Tamil', 'Telugu', 'German',
English 'Chinese', 'English'}
French 7
German {'French', 'Malayalam', 'Tamil', 'Telugu', 'German',
'English'}
{'Malayalam', 'Tamil', 'Telugu', 'German', 'English'}
Malayalam
{'Tamil', 'Telugu', 'German', 'English'}
set()
Traceback (most recent call last):
File "<string>", line 31, in <module>
NameError: name 'Language' is not defined
Enter the {'German', 'English,', 'French,'}
Languages True
separated {'Chinese', 'German', 'English,', 'French,'}
by space: {'German', 'Telugu', 'Chinese', 'Tamil', 'English,',
English, 'Malayalam', 'French,'}
French, 7
German {'German', 'Telugu', 'Tamil', 'English,', 'Malayalam',
'French,'}
{'German', 'Telugu', 'Tamil', 'English,', 'Malayalam',
'French,'}
German
{'Telugu', 'Tamil', 'English,', 'Malayalam', 'French,'}
set()
Traceback (most recent call last):
File "<string>", line 31, in <module>
NameError: name 'Language' is not defined
II Enter input {'Chasis': 'Hatchback', 'Engine': 'VCylinder',
pair for 'Capacity': '1000cc', 'Variant': 'Petrol'}
Key VCylinder
'Chasis' : VCylinder
Hatchback {'Chasis': 'Hatchback', 'Engine': 'VCylinder',
Enter input 'Capacity': '1000cc', 'Variant': 'Petrol', 'Cost': '75000'}
pair for {'Chasis': 'Hatchback', 'Engine': 'TwinCylinder',
Key 'Capacity': '1000cc', 'Variant': 'Petrol', 'Cost': '75000'}
'Engine' : 75000
VCylinder {'Chasis': 'Hatchback', 'Engine': 'TwinCylinder',
Enter input 'Capacity': '1000cc', 'Variant': 'Petrol'}
pair for ('Variant', 'Petrol')
Key {'Chasis': 'Hatchback', 'Engine': 'TwinCylinder',
'Capacity' : 'Capacity': '1000cc'}
1000cc {'Chasis': 'Hatchback', 'Capacity': '1000cc'}
Enter input {}
pair for Traceback (most recent call last):
Key File "<string>", line 35, in <module>
'Variant' : NameError: name 'automobile' is not defined
Petrol
Enter input {'Chasis': '1', 'Engine': '2', 'Capacity': '3', 'Variant':
pair for '4'}
Key 2
'Chasis' : 1 2
Enter input {'Chasis': '1', 'Engine': '2', 'Capacity': '3', 'Variant': '4',
pair for 'Cost': '75000'}
Key {'Chasis': '1', 'Engine': 'TwinCylinder', 'Capacity': '3',
'Engine' : 2 'Variant': '4', 'Cost': '75000'}
Enter input 75000
pair for {'Chasis': '1', 'Engine': 'TwinCylinder', 'Capacity': '3',
Key 'Variant': '4'}
'Capacity' : ('Variant', '4')
3 {'Chasis': '1', 'Engine': 'TwinCylinder', 'Capacity': '3'}
Enter input {'Chasis': '1', 'Capacity': '3'}
pair for {}
Key Traceback (most recent call last):
'Variant' : File "<string>", line 35, in <module>
4 NameError: name 'automobile' is not defined
III Enter {'Pillars': '100', 'Floors': '5', 'Windows': '50'}
number of Contents of the Dictionary = {'Pillars': '100', 'Floors':
'Pillars': '5', 'Windows': '50'}
100 Checking if Pillars is a key in dictionary = True
Enter Checking if Walls is not a key in dictionary = True
number of Cannot check with pair value 50 in dictionary (True -
'Floors': 5 pair can be checked, False - pair cannot be checked =
Enter False
number of Pair values in the dictionary =
'Windows': 100
50 5
50
Length of the dictionary = 3
Sort the keys of the dictionary in alphabetical order =
['Floors', 'Pillars', 'Windows']
Enter {'Pillars': 'a', 'Floors': 'b', 'Windows': 'c'}
number of Contents of the Dictionary = {'Pillars': 'a', 'Floors': 'b',
'Pillars': a 'Windows': 'c'}
Enter Checking if Pillars is a key in dictionary = True
number of Checking if Walls is not a key in dictionary = True
'Floors': b Cannot check with pair value 50 in dictionary (True -
Enter pair can be checked, False - pair cannot be checked =
number of False
'Windows': Pair values in the dictionary =
c a
b
c
Length of the dictionary = 3
Sort the keys of the dictionary in alphabetical order =
['Floors', 'Pillars', 'Windows']
8. Output
I.
{'German', 'English,', 'French,'}
True
{'Chinese', 'German', 'English,', 'French,'}
{'German', 'Telugu', 'Chinese', 'Tamil', 'English,', 'Malayalam', 'French,'}
7
{'German', 'Telugu', 'Tamil', 'English,', 'Malayalam', 'French,'}
{'German', 'Telugu', 'Tamil', 'English,', 'Malayalam', 'French,'}
German
{'Telugu', 'Tamil', 'English,', 'Malayalam', 'French,'}
set()
Traceback (most recent call last):
File "<string>", line 31, in <module>
NameError: name 'Language' is not defined
II.
{'Chasis': 'Hatchback', 'Engine': 'VCylinder', 'Capacity': '1000cc', 'Variant': 'Petrol'}
VCylinder
VCylinder
{'Chasis': 'Hatchback', 'Engine': 'VCylinder', 'Capacity': '1000cc', 'Variant': 'Petrol',
'Cost': '75000'}
{'Chasis': 'Hatchback', 'Engine': 'TwinCylinder', 'Capacity': '1000cc', 'Variant':
'Petrol', 'Cost': '75000'}
75000
{'Chasis': 'Hatchback', 'Engine': 'TwinCylinder', 'Capacity': '1000cc', 'Variant':
'Petrol'}
('Variant', 'Petrol')
{'Chasis': 'Hatchback', 'Engine': 'TwinCylinder', 'Capacity': '1000cc'}
{'Chasis': 'Hatchback', 'Capacity': '1000cc'}
{}
Traceback (most recent call last):
File "<string>", line 35, in <module>
NameError: name 'automobile' is not defined
III.
{'Pillars': '100', 'Floors': '5', 'Windows': '50'}
Contents of the Dictionary = {'Pillars': '100', 'Floors': '5', 'Windows': '50'}
Checking if Pillars is a key in dictionary = True
Checking if Walls is not a key in dictionary = True
Cannot check with pair value 50 in dictionary (True - pair can be checked, False -
pair cannot be checked = False
Pair values in the dictionary =
100
5
50
Length of the dictionary = 3
Sort the keys of the dictionary in alphabetical order = ['Floors', 'Pillars', 'Windows']
9. Result
The operations for the sets and dictionaries were successfully implemented through python
program.
The clear() method empties the set, whereas del keyword will delete the set completely:
Dictionary is mutable. We can add new items or change the value of existing items using
assignment operator. If the key is already present, value gets updated, else a new key:
value pair is added to the dictionary.
pop(key[,d]) - Remove the item with key and return its value or d if key is not found. If
d is not provided and key is not found, raises KeyError.
popitem() - Remove and return an arbitrary item (key, value). Raises KeyError if the
dictionary is empty.
We can test if a key is in a dictionary or not using the keyword in. The membership test
is for keys only, not for values. For example,
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
# membership tests for key only not value
# Output: False
print(49 in squares)
Ex.No: 6 Implementing Programs using Functions
Date :
1. Problem Statement: Write a python program to implement Factorial of a number, largest
number in a list, area of shape using functions.
2. Expected Learning Outcomes: Train the students to understand the basics of functions.
3. Problem Analysis:
B. Expected Output:
II.
Step 1: Start
Step 2: Create an empty list
Step 3: Read list elements from User
Step 4: Assign first number in list to variable "max"
Step 5: Use for loop compare each number with "max" value
Step 6: Assign the largest value to "max'
Step 7: Repeat Step 5 and 6 until reach the last element of the list
Step 8: Print max as largest number in the list
III.
Step 1: Select the shape
Step 2: If it is rectangle do the following
Step 2.1: Enter the width of the rectangle.
Step 2.2: Enter the Height of the rectangle.
Step 2.3: Calculate the area of the rectangle by multiplying the width and
height of the rectangle.
Step 2.4: Assign the area of the rectangle to the area variable.
Step 2.5: print the area of the rectangle.
Step 3: If it is triangle do the following
Step 3.1: Enter the breadth of the triangle
Step 3.2: Enter the Height of the triangle
Step 3.3: Calculate the area of the rectangle by multiplying the breadth and
height of the triangle
Step 3.4: Assign the area of the triangle to the area variable.
Step 3.5: print the area of the triangle
Step 4: If it is square do the following
Step 4.1: Enter the side of the square
Step 4.2: Calculate the area of the square by multiplying the 4 sides
Step 4.3: Assign the area of the Square to the area variable.
Step 4.4: Print the area of the square
Step 5: If it is circle do the following
Step 5.1: Enter the radius of the circle
Step 5.2: Calculate the area of the circle by 𝐴 = 𝜋𝑟 2
Step 5.3: Assign the area of the circle to the area variable.
Step 5.4: Print the area of the circle
6. Coding:
a. Write a program to find the factorial of a number.
# driver code
if __name__ == "__main__" :
7. Test case :
Input Output
I Enter the value of N:4 The factorial of the given number 4
is:
24
Enter the value of N:-3 The factorial of the given number -
3 is:
Please enter the value of N: a invalid literal for int() with base 10:
'a'
II Enter the list of elements:[5,8,3 9,2] The largest number in the list is 9
Enter the list of elements:[33,25,28,34 The largest number in the list is 34
19,2]
III Enter name of the shape: Rectangle
Enter rectangle's length: 4
Enter rectangle's breadth:3 Area of Rectangle:12
Enter name of the shape: Triangle
Enter triangle's height length: 4
Enter triangle's breadth length: 3 Area of Triangle: 6
Enter name of the shape: Square
Enter square's side length: 4 Area of Square: 16
Enter name of the shape: Circle
Enter circle's radius length: 4 Area of Circle: 50.24
Enter rectangle's length: s could not convert string to float: 's'
8. Output :
9. Result
Factorial of a number, Largest number in a list, Area of different shapes are successfully
implemented through functions.
10. Viva Questions
To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
B. Define function.
A function is a block of code which only runs when it is called.You can pass data, known as
parameters, into a function.A function can return data as a result.
E. What is Recursion?
Python also accepts function recursion, which means a defined function can call itself.
Date :
2. Expected Learning Outcomes: Train the students to understand the basics of Strings
concepts.
3. Problem Analysis:
4. A. Expected Input:
B. Expected Output:
I.
Step 1: Get the input from the user and store the value in a
Step 2: Use slice statement and read the string
. Step 3: Print the reverse String
II.
Step 1: Get the input string from user and store in x
Step 2: Define a palindrome function
Step 3: Use slicing function and reverse the string
Step 4: check both the string are same
Step 5: If yes, The string is Palindrome
Step 6: If not, The string is not a Palindrome
III.
Step 1: Read the string from user and store in x
Step 2: Read the char to be count and store in y
Step 3: Use count function to count the number of characters
Step 4: Display the output
IV.
Step 1: Read the string from user and store in x
Step 2: Read the char to be replaced and store in a,b
Step 3: Use replace function to replace the characters
Step 4: Display the output
6. Coding:
def isPalindrome(x):
return x == x[::-1]
x = input("Please enter the string x:")
y = isPalindrome(x)
if y:
print("Yes,The string is Palindrome ")
else:
print("No,The string is not a Palindrome")
III. Write a program to count a character from a given string
7. Test case :
Input Output
I Please enter the string a:welcome Reverse string is:
emoclew
Please enter the string a: python programming Reverse string is:
gnimmargorp nohtyp
II Please enter the string x:malayalam Yes,The string is Palindrome
Please enter the string x:modem No,The string is not a Palindrome
III Please enter the string x:knowledge count of e in given string is: 2
Please enter the char to be count :e
Please enter the string x:python count of g in given string is: 0
Please enter the char to be count :g
IV Please enter the string x:good the replaced string is gaad
Please enter which the char to be replace :o a the replaced string is gaod
Please enter how many times u want to replace the
char:1
8. Output :
9. Result
The programs Reverse a string , palindrome, character count, replacing characters using
Strings are successfully implemented.
● Arrays in python can only contain elements of same data types i.e., data type of
array should be homogeneous. It is a thin wrapper around C language arrays and
consumes far less memory than lists.
● Lists in python can contain elements of different data types i.e., data type of lists
can be heterogeneous. It has the disadvantage of consuming large memory.
Python comprehensions, like decorators, are syntactic sugar constructs that help build
altered and filtered lists, dictionaries, or sets from a given list, dictionary, or set. Using
comprehensions saves a lot of time and code that might be considerably more verbose
(containing more lines of code).
Lambda is an anonymous function in Python, that can accept any number of arguments,
but can only have a single expression. It is generally used in situations requiring an
anonymous function for a short time period.
Ex.No: 8 Programs using written modules and Python Standard
Libraries
Date :
5. Problem Statement: Write a python program using python runnable code called modules
and use python standard libraries.
6. Expected Learning Outcomes: Train the students to understand the basic of modules and
libraries available in python
7. Problem Analysis:
I. Use python math module to compute various mathematical operations.
II. Compute the Mean, Median, Mode, Quartiles and Standard deviation using
Numpy and pandas libraries.
8. A. Expected Input:
I. Enter the set of 3 numbers for finding the square root, Factorial and log base2
:3,5,10
II. Take a set of eight numbers as input.
Set of frequencies: [11, 21, 34, 22, 27, 11, 23, 21]
B. Expected Output:
V.
Mean= 21.25
Mean= 21.25
Median 21.5
Mode [11, 21]
Mode 11
Quartiles (16.0, 21.5, 25.0)
Standard Deviation Simple Method: 7.1545440106270926
Standard Deviation using Numpy: 7.1545440106270926
5. Algorithm:
IV. Step 1: Get three Numbers from user and store it in a, b, and c
Step 2: Compute Square root of a and display the result
Step 3: Compute factorial of b and display the result
Step 4: Compute log base 2 of c and display the result
Step 5: Stop
V.
Step1: Take a list of 8 Numbers.
Step2: Compute the Mean value by simple Computation and print it.
Step3: Compute the Mean value using numpy method and print it.
Step4: Compute the Median value by simple Computation and print it.
Step5: Compute the Mode value by simple Computation and print it.
Step6: Compute the Mode value using numpy method and print it.
Step7: Compute the IQR (Inter Quartile Range) by simple Computation and print
it.
Step8: Compute the Standard Deviation by simple Computation and print it.
Step9: Compute the Standard Deviation using Numpy and print it.
Step 10: Stop
6. Coding:
IV. Write a program to compute Square root , Factorial and Log base 2 using math
module in python
import math as
a,b,c = input('Enter the set of 3 numbers for finding the square root , Factorial and
log base2 :').split(',')
a = int(a)
b = int(b)
c = int(c)
print('Square root ',m.sqrt(a))
print('Factorial ',m.factorial(b))
print('Log base 2 ',m.log2(c))
V. Write a program to compute mean, median, mode, IQR and Standard Deviation
using Numpy, Pandas and Scipy in python
import numpy as n
from collections import Counter
from scipy import stats
# Finding Mean by simple Computation
a= [11, 21, 34, 22, 27, 11, 23, 21]
mean = sum(a)/len(a)
print (mean)
# Finding Mean using numpy method
mean = np.mean(a)
print (mean)
# Finding Median by simple Computation.
def median(nums):
nums.sort()
if len(nums)%2 == 0:
return int(nums[len(nums)//2-1]+nums[len(nums)//2])/2
else:
return nums[len(nums)//2]
print (median(a))
# Finding Mode by simple Computation
data = dict(Counter(a))
mode = [k for k, v in data.items() if v == max(list(data.values()))]
print (mode)
# Finding Mode using numpy method
print (stats.mode(a)[0][0])
# Finding Quartiles by simple method
def quartiles(nums):
nums=sorted(nums)
Q1 = median(nums[:len(nums)//2])
Q2 = median(nums)
if len(nums)%2 == 0:
Q3 = median(nums[len(nums)//2:])
else:
Q3 = median(nums[len(nums)//2+1:])
return Q1,Q2,Q3
def median(nums):
nums.sort()
if len(nums)%2 == 0:
return int(nums[len(nums)//2-1]+nums[len(nums)//2])/2
else:
return nums[len(nums)//2]
print (quartiles(a))
# Find Standard deviation by simple computation
n=len(a)
std=(sum(map(lambda x: (x-sum(a)/n)**2,a))/n )**0.5
print(std)
# Find Standard deviation using numpy method
print (np.std(a))
8. Test case:
Input Output
II. 0,0,0 Square root 0.0
Factorial 1
ValueError: math domain
error
100,2,100 Square root 10.0
Factorial 2
Log base 2
6.643856189774724
III. [9, 8, 31, 20, 0, 31, 31, 20] Mean = 18.75
Mean = 18.75
Median = 20.0
Mode = [31]
Mode = 31
Quartiles = (8.5, 20.0, 31.0)
Strandard Deviation =
11.266654339243749
Strandard Deviation =
11.266654339243749
['a', 100, 310, 200, 100, 1, 100, 20] TypeError: cannot perform
reduce with flexible type
11. Output
12. Result
Few most important modules including Math, Numpy array, pandas and Scipy were
successfully implemented through python program.
Use the asterisk (*) as a wild card. The following statement will import every function
and property contained in the math package.
Pandas is a Python library for data analysis. ... Pandas is built on top of two core Python
libraries—matplotlib for data visualization and NumPy for mathematical operations.
Pandas acts as a wrapper over these libraries, allowing you to access many of matplotlib's
and NumPy's methods with less code.
SciPy is an open-source Python library which is used to solve scientific and mathematical
problems. It is built on the NumPy extension and allows the user to manipulate and
visualize data with a wide range of high-level commands.
Ex.No: 9 Implementing real-time/technical applications using File
handling.
Date :
2. Expected Learning Outcomes: Train the students to understand the basics of file
handling operations.
3. Problem Analysis:
a. Using read, write & append operations in file concepts implement the copy
contents of the first file into the second file
b. Using split() function implement the word count from a given text or sentence.
c. Using string split() function & max() function implement the longest word from
sentence
4. A. Expected Input:
B. Expected Output:
5. Algorithm:
I.
Step1: Start
Step2: Create text files first.txt and save with some contents & second.txt with
Empty contents
Step3: open first.txt in ‘r’ mode
Step2: read the contents of first.txt.
Step3: open second.txt in ‘a’ mode and will append the content of first.txt into
second.txt.
Step 6: open second.txt
Step 7: Stop
II.
Step 1: Start
Step 2: Get the string from User
Step 3: Read list elements from User
Step 4: Use Split function breaks the string into a list iterable with space as a
delimiter
Step 5: if the split() function is used without specifying the delimiter space is
allocated as a default delimiter.
Step 6: Print number of words in string
III.
Step 1: Start
Step 2: Get the string from User
Step 3: Read sentence from user
Step 4: Use Split function to convert it to list.
Step 5: After splitting to use max() function with keyword argument key=len
Step 6: Print longest word from sentence
6. Coding:
b. Write a program to find find word count from a given text or sentence.
Input Output
i Myinputfile.txt: Myoutput file.txt:
Hi this is my first copy file python program Hi this is my first copy file python
program
Myinputfile.txt: Myoutputfile.txt:
7764gffghhg 7764gffghhg
ii The original string is : Tutorials point is a The number of words in string are : 6
learning platform
The original string is : This is my test string The number of words in string are : 8
for word count problem
iii Enter sentence: Longest word is: twisted
Tongue tied and twisted just an earth And its length is: 7
bound misfit I
Enter sentence: Longest word is: exercise
This is my test string for longest word And its length is: 8
count exercise
8. Output :
9. Result
Real-time/technical applications (copy from one file to another, word count, longest
word) implemented through File handling operations.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, full address
of the file should be written on place of filename.
File_object.close()
Ex.No : 10 Real-time/technical applications using Exception handling
Date :
3. Problem Analysis:
4. A. Expected Input:
a. Enter a:10
Enter b:0
b. Enter Age : 19
c. Enter marks of the first subject: 85
Enter marks of the second subject: 95
Enter marks of the third subject: 99
Enter marks of the fourth subject: 93
Enter marks of the fifth subject: 100
B. Expected Output:
5. Algorithm:
a.
Step 1: Get the input from the user and store the value in a & b
Step 2: Use try & catch with division statement and read the input values
. Step 3: Print the ZeroDivisionError
b.
Step 1: Get the input from user and store in x
Step 2: Use a conditional check statement and read the string
Step 3: If yes, You are Eligible for Vote
Step 6: If not, You are Not Eligible for Vote
III.
Step 1: Get the input from the user and store the value in sub1, sub2 ,sub3,
sub4 & sub5
Step 3: Use Avg computation and to get Avg value
Step 4: Display the output
6. Coding:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")
7. Test case :
Input Output
I Enter a:10 ZeroDivisionError: division by zero
Enter b:0
Enter a:10 Will not throw division by zero
Enter b:5
I Enter Age : 19 Yes,You are Eligible for Vote
Enter Age : 17 No, You are not Eligible for Vote
III Enter marks of the first subject: 85
Enter marks of the second subject: 95
Enter marks of the third subject: 99
Enter marks of the fourth subject: 93 Grade: A
Enter marks of the fifth subject: 100
8. Output :
9. Result
A list of common exceptions that can be thrown from a standard Python program is
given below.
● We can use the exception variable with the except statement. It is used by using the as
keyword. this object will return the cause of the exception.
.
● Without the Exception, It will not interrupt the program execution and will not through
a exception message.
Ex.No: 11 Exploring Pygame
Date :
3. Description
Pygame
⮚ Pygame is a cross-platform set of Python modules which is used to create video games.
⮚ It consists of computer graphics and sound libraries designed to be used with the Python
programming language.
⮚ Pygame was officially written by Pete Shinners to replace PySDL.
⮚ Pygame is suitable to create client-side applications that can be potentially wrapped in a
standalone executable.
Before learning about pygame, we need to understand what kind of game we want to develop.
Pygame Installation
Before installing Pygame, Python should be installed in the system, and it is good to have 3.6.1
or above version because it is much friendlier to beginners, and additionally runs faster. There
are mainly two ways to install Pygame, which are given below:
1. Installing through pip: The good way to install Pygame is with the pip tool (which is
what python uses to install packages). The command is the following:
PIP is a tool that is used to install python packages. PIP is automatically installed with Python
2.7. 9+ and Python 3.4+. Open the command prompt and enter the command shown below to
check whether pip is installed or not.
pip install package_name
pip will look for that package on PyPI and if found, it will download and install the package on
your local system.
pip can be downloaded and installed using command-line by going through the following steps:
● Download the get-pip.py file and store it in the same directory as python is installed.
Change the current path of the directory in the command line to the path of the directory where
the above file exists.
Installing through an IDE: The second way is to install it is through an IDE and here we are
using Pycharm IDE. Installation of pygame in the pycharm is straightforward. We can install it
by running the above command in the terminal or use the following steps:
o It will display the search box. Search the pygame and click on the install package button.
To check whether the pygame is properly installed or not, in the IDLE interpreter, type the
following command and press Enter:
import pygame
If the command runs successfully without throwing any errors, it means we have successfully
installed Pygame and found the correct version of IDLE to use for pygame programming.
pygame.init() - This is used to initialize all the required module of the pygame.
pygame.event.get()- This is used to empty the event queue. If we do not call this, the window
messages will start to pile up and, the game will become unresponsive in the opinion of the
operating system.
pygame.QUIT - This is used to terminate the event when we click on the close button at the
corner of the window.
Pygame Blit
The pygame blit is the process to render the game object onto the surface, and this process is
called blitting. When we create the game object, we need to render it. If we don't render the
game objects and run the program, then it will give the black window as an output.
Blitting is one of the slowest operations in any game so, we need to be careful to not to blit much
onto the screen in every frame. The primary function used in blitting is blit(), which is:
blit()
surface = pygame.Surface((100,100))
The above line creates a blank 24-bit RGB image that's 100*100 pixels with the default black
color.
4. Result
Thus to study and explore Pygame was successfully completed.
5. Viva Questions
Date :
1. Problem Statement: Write a python program to develop a game activity like bouncing
ball, elliptical orbit etc. using Pygame
3. Problem Analysis:
a. Using pygame. image. Load() the ball image has been opened and an infinite loop
has been created to make the ball move continuously and reverse the direction of ball
if it hits the edges. Pygame provides move() method to make an object move smoothly
across the screen.Using fill() method the surface background color is filled.we also
need to render the moving object on the window In pygame, this is called blitting of
an object and implemented with blit() method. flip () method is used to make all
image visible.
b. Using display.setmode() set the screen size .Let us set the x and y radius of ellipse.
starting from degree 0 ending with 360 degrees in increments of 10 degrees calculate
the (x1, y1) coordinates to find a point in the elliptical orbit.Using (degree * 2 *
math.pi / 360) x1 = (type conversion int) (math.cos(radians) * xradius) +
screensize/2 formula convert degree to radians.Using pygame.draw.ellipse() and
pygame.draw.circle() a centre circle ,ellipse and another smaller circle on the ellipse
are drawn.
4. A. Expected Input:
IV.
V.
6. Algorithm:
I.
Step 1: Start the program
Step 2: Set the screen size and background colour
Step 3: Set the speed of the moving ball
Step 4: Create a graphical window using set_mode()
Step 5: Set the caption
Step 6: Load the ball image and create a rectangle area covering the image.
Step 7: Use blit() method to copy the pixel color of the ball to the screen.
Step 8 : Set the background color of the screen and use the flip() method to
make all the images visible
Step 9: Move the ball in specified speed.
Step 10: If the ball hits the edges of the screen reverse the direction.
Step 11: Create an infinite loop and repeat the steps 9 and 10 until the user exits
the program.
Step 12: Stop the program
II.
Step 1: Start
Step 2: Set screen size and caption.
Step 3: Create clock variable
Step 4: Set the x and y radius of the ellipse.
Step 5: Starting from the degree 0 ending with 360 degrees in increments of 10
degrees calculate the (x1,y1) coordinates to find a point in the elliptical orbit.
Step 6: Convert degree to radiants (degree * 2*math.pi/360)
Step 7 : Set the background color ,draw the center circle ,ellipse and another
smaller circle on the ellipse
Step 8: Refresh the screen for every 5 clock ticks.
Step 9: Repeat the steps 4 to 8 until user quits the program.
Step 10: Stop
7. Coding:
a. Write a program to develop a game activity like bouncing ball using Pygame
import pygame,sys
pygame.init()
size=width,height=1000,600
speed=[2,2]
screen=pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball=pygame.image.load("D:\IMAGES\Small ball.jpg")
ballrect=ball.get_rect()
while(True):
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
ballrect=ballrect.move(speed)
if ballrect.left<0 or ballrect.right>width:
speed[0]=-speed[0]
if ballrect.top<0 or ballrect.bottom>height:
speed[1]=-speed[1]
screen.fill("white")
screen.blit(ball,ballrect)
pygame.display.flip()
b. Write a program to develop a game activity like elliptical orbit using Pygame
import pygame
import math
import sys
pygame.init()
screen=pygame.display.set_mode((600,500))
pygame.display.set_caption("Elliptical Orbit")
clock=pygame.time.Clock()
while(True):
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
xRadius=250
yRadius=100
for degree in range(0,360,10):
x1=int(math.cos(degree*2*math.pi/360)*xRadius)+300
y1=int(math.sin(degree*2*math.pi/360)*yRadius)+150
screen.fill("black") #erase the screen by filling it with black color
pygame.draw.circle(screen,(255,70,0),[300,150],40)
pygame.draw.ellipse(screen,pygame.Color("yellow"),[50,50,500,200],1)
pygame.draw.circle(screen,(0,255,0),[x1,y1],20)
pygame.display.flip()
clock.tick(5)
8. Output :
I.
II.
9. Result
Thus simulation of game activity like bouncing ball and elliptical orbit using pygame
were successfully implemented and output was obtained.
To draw a circle in your pygame project you can use draw. circle() function.
B. Is pygame a GUI?
Pygame GUI is a module to help you make graphical user interfaces in for games written
in pygame.
*Create a pygame. Surface object with a per-pixel alpha format and with the size of
the shape.
*Draw the shape on the Surface.
*Rotate the Surface with the shape around its center.
* Blit the Surface with the shape onto the target Surface