FINAL Ge3171 Python Lab Manual
FINAL Ge3171 Python Lab Manual
LABORATORY MANUAL
For
PEO-2: Demonstrate ethical values, effective communication and team skills in theirprofession and
adapt to current trends through lifelong learning.
PSO-1: Understand, analyze and develop computer applications in data Mining/ Analytics, Cloud
Computing, Networking, Security, etc. to meet the requirements of industry and society.
PSO-2: Enrich the ability to design and develop software and qualify for Employment Higher
studies and Research.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for
the public health and safety, and the cultural, societal, and environmental considerations
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
lOMoARcPSD|5477448
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilitiesand norms of
the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member orleader in
diverse teams, and in multidisciplinary settings.
12.Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technologicalchange.
lOMoARcPSD|5477448
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
A. 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.)
B. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
C. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns,
pyramid pattern)
F. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
H. Implementing programs using written modules and Python Standard Libraries (pandas, numpy.
Matplotlib, scipy)
I. Implementing real-time/technical applications using File handling. (copy from one file to another, word
count, longest word)
L. Developing a game activity using Pygame like bouncing ball, car race etc.
lOMoARcPSD|5477448
INDEX
11 Exploring Pygame
Date :
1. Problem statement :Identification and solving of simple real life or scientific or technical
problems, and developing flow charts for Electricity Billing, Retail shop billing, Sin series,
weight of a motorbike, Weight of a steel bar, compute Electrical Current in Three Phase AC
Circuit.
2. Expected Learning outcomes :It helps the students to understand to draw flowcharts for simple
real time or scientific or technical problems.
A. Electricity Billing
i. Algorithm:
Step 1: Start the algorithm
Step 2: Get the number of units, U as
input.
Step 3: i)For first 100 units , there is no
bill.
ii) For units between 101 to 200, assign Rs 2 for a unit.
iii) For units greater than 200, calculate the bills by assigning Rs. 3 for each unit.
Step 4: Print the bill
Step 5: Stop the algorithm
ii. Program
curr=int(input("Enter current month reading"))
prev=int(input("Enter previous month reading"))
consumed=curr - prev
if(consumed >= 1 and consumed <= 100):
amount=0
print("your bill is Rs.", amount)
elif(consumed > 100 and consumed <=200):
amount=consumed * 2
print("your bill is Rs.", amount)
elif(consumed > 300):
amount=consumed * 3
print("your bill is Rs.", amount)
else:
print("Invalid reading")
lOMoARcPSD|5477448
iii. Flowcharts:
Start
Get
the
unit U
Yes 𝐼𝑓𝑈 No
≤
100
𝐼𝑓𝑈
No
>
Bill = 0
100
Yes
𝐼𝑓𝑈
>
Bill = U * 2
200
Yes
Bill = U * 3
Print
bill
Stop
ii. Program
iii. Flowcharts:
Start
𝐵=0
Enter i
𝐵 = 𝐵 + (𝑖𝑡 ∗ 𝑞
∗ 𝑝)
No
Print B
Stop
lOMoARcPSD|5477448
C. Sine Series:
D.
i. Algorithm:
Step 1: Start the algorithm
Step 2: Get x and i
Step 3: Initialize fact=1 and i=1
Step 4: for k=1 to j
Calculate fact as fact * k
Find the factorial as x
Increment i by 2.
Step 5: Repeat step 4 for i times
Step 6: Display the sine series
result Step 7: Stop the algorithm.
ii. Program
import math
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
sine = 0
for i in range(n):
sign = (-1)**i
pi=22/7
y=x*(pi/180)
sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign
print(sine)
iii. Flowcharts:
lOMoARcPSD|5477448
Start
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
i. 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.
ii. Program
Wf=10#front weight
Wr=40# rear weight
WB=50#wheelbase
X =Wr*WB/ Wf+Wr
print("Weight of bike",X)
lOMoARcPSD|5477448
iii. Flowcharts:
Start
𝑆𝑤𝑖𝑡𝑐ℎ 𝑀
Yes 𝑊 = 315 𝑘𝑔
𝐶𝑎𝑠𝑒
= 𝐶ℎ𝑜𝑝𝑝𝑒𝑟
No
Yes 𝑊 = 250 𝑘𝑔
𝐶𝑎𝑠𝑒
= 𝐶𝑟𝑢𝑖𝑠𝑒𝑟
No
Yes 𝑊 = 115 𝑘𝑔
𝐶𝑎𝑠𝑒
= 𝑆𝑐𝑜𝑜𝑡𝑒𝑟
No
Yes 𝑊 = 80 𝑘𝑔
𝐶𝑎𝑠𝑒
= 𝑀𝑜𝑝𝑝𝑒𝑑
No
Weight(W) cannot calculated
Print w
𝑆𝑡𝑜𝑝
lOMoARcPSD|5477448
i. 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.
ii. Flowcharts:
Start
Get d
𝐼𝑓 𝑑 ≥ 8 𝑚𝑚
Yes
≤ 20 𝑚𝑚
𝑊 = (𝑑 ∗ 𝑑 )/162
No
Print not
Ghahvjajkiljable Print w
𝑆𝑡𝑜𝑝
iii. Program:
D=10
L=100
W=(D**2)*L)/162
print (“Weight of steel bar”, W)
lOMoARcPSD|5477448
i. Algorithm:
Step 1: Start the algorithm
ii. Flowcharts:
Start
Get P, Pf, V
𝐼 = 𝑃/√3 ∗ 𝑉 ∗ 𝑃𝑓
Print 𝐼
𝑆𝑡𝑜𝑝
iii. Program
from math import cos,acos,sqrt
R = 20.;# in ohm
X_L = 15.;# in ohm
V_L = 400.;# in V
f = 50.;# in Hz
#calculations
V_Ph = V_L/sqrt(3);# in V
Z_Ph = sqrt( (R**2) + (X_L**2) );# in ohm
I_Ph = V_Ph/Z_Ph;# in A
I_L = I_Ph;# in A
print ("The line current in A is",round(I_L,2))
# pf = cos(phi) = R_Ph/Z_Ph;
R_Ph = R;# in ohm
phi= acos(R_Ph/Z_Ph);
# Power factor
pf= cos(phi);# in radians
print ("The power factor is : ",pf,"degrees lag.")
P = sqrt(3)*V_L*I_L*cos(phi);# in W
print ("The power supplied in W is",P)
lOMoARcPSD|5477448
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.
a.Viva voice
Date :
1. Problem Statement :Write a python programs to exchange the values of two variables,
circulate the values of n variables, distance between two points using simple statements
and expressions.
2. Expected Learning Outcomes :It helps the students to understand the functionality of
simple statements and expressions.
3. Problem Analysis:
I. Using simple statement exchange the values of two variables should be
implemented by getting two integer values x,yas 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
lOMoARcPSD|5477448
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.
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'"
lOMoARcPSD|5477448
8. Output:
i) enter x value :
77 enter y value :
105
After swapping value of x = 105
After swapping value of y = 77
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.
which means it is a number that has a decimal place. Floats are used when more precision is
needed.
D. What is a string?
A string is a data type used in programmingto 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:
III.
lOMoARcPSD|5477448
*
**
***
****
*****
******
*******
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 ‘*’
lOMoARcPSD|5477448
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
N = int(input("Please enter the value of N:"))
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('\nThe Square of the given number',N,'is:',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=' ')
print('\n The Sum of the given number',N,'is: ',Sum,end=' ')
II. Write a program to display number pattern
7. Test case :
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
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]
lOMoARcPSD|5477448
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
lOMoARcPSD|5477448
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.
6. Coding:
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
space: 1 2 3 4 34
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
lOMoARcPSD|5477448
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']
lOMoARcPSD|5477448
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.
lOMoARcPSD|5477448
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'}
lOMoARcPSD|5477448
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.
lOMoARcPSD|5477448
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.
lOMoARcPSD|5477448
#Step
36 = list(map(str, input("Enter the Languages separated by space: ").split()))
list
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)
lOMoARcPSD|5477448
#Step
x37= 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.
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')
lOMoARcPSD|5477448
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
lOMoARcPSD|5477448
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.
B. What will be the output, if you try to remove an item which is not in the list ?
If the item to remove does not exist, remove() will raise an error.
If the item to remove does not exist, discard() will NOT raise an error.
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)
lOMoARcPSD|5477448
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:
Area of Triangle: 6
Area of Square: 16
Area of Circle: 50.24
5. Algorithm:
I.
Step 1: Start
Step 2: Declare Variable n, fact, i
Step 3: Read number from User
Step 4: Initialize Variable fact=1 and i=1
Step 5: Repeat Until i<=number
5.1 fact=fact*i
5.2 i=i+1
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
lOMoARcPSD|5477448
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:
lOMoARcPSD|5477448
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.
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:
5. Algorithm:
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:
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:
gnimmargorpnohtyp
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.
lOMoARcPSD|5477448
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.
Decorators in Python are essentially functions that add functionality to an existing function
in Python without changing the structure of the function itself. They are represented
the @decorator_name in Python and are called in a bottom-up fashion.
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.
lOMoARcPSD|5477448
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
lOMoARcPSD|5477448
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 m
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 np
from collections import Counter
from scipy import stats
# Finding Mean by simple Computation
a= [11, 21, 34, 22, 27, 11, 23, 21]
#a=[9, 8, 31, 20, 0, 31, 31, 20]
mean = sum(a)/len(a)
print("mean",mean)
lOMoARcPSD|5477448
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.
lOMoARcPSD|5477448
a. import module.
b. from module import function.
c. from module import *
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.
lOMoARcPSD|5477448
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
lOMoARcPSD|5477448
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:
7. Test case :
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 The number of words in string are : 8
string 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.
lOMoARcPSD|5477448
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()
lOMoARcPSD|5477448
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
lOMoARcPSD|5477448
b.
Step 1: Get the input from user and store in x
Step 2: Use a conditional check statement and read the string
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")
VI. Write a program to display voter’s age validity
# input age
age = int(input("Enter Age : "))
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
Thus The programs real-time/technical applications using Exception handling(divide by zero error,
voter’s age validity, student mark range validation) are successfully implemented.
Whenever an exception occurs, the program stops the execution, and thus the further
code is not executed.
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.
lOMoARcPSD|5477448
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.
lOMoARcPSD|5477448
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.
To install Pygame, open the command prompt and give the command as shown below:
pip install pygame
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.
lOMoARcPSD|5477448
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.
PygameBlit
The pygameblit 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()
To add an image on the window, first, we need to instantiate a blank surface by calling the Surface
constructor with a width and height tuple.
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. For the transparent initialization of Surface, pass the SRCALPHA argument.
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.Usingfill() 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.Usingpygame.draw.ellipse() and
pygame.draw.circle() a centre circle ,ellipse and another smaller circle on the ellipse
are drawn.
4. A. Expected Input:
5. B. Expected Output:
IV. 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.
lOMoARcPSD|5477448
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()
lOMoARcPSD|5477448
b. Write a program to develop a game activity like elliptical orbit using Pygame
importpygame
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.
lOMoARcPSD|5477448
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