lab manual (1)
lab manual (1)
GE3171
PROBLEM SOLVING AND PYTHON PROGRAMMING
LABORATORY
(LABORATORY MANUAL)
(R-2021)
I SEMESTER
Asst. Professor/IT
VISION:-
To become a global center of excellence in Computer Science and Engineering with quality
learning and research in embracing future technologies with ethical values.
MISSION:-
• To impart quality education to Computer Science students irrespective of the Socio-
economical discriminations and enlighten their minds to achieve academic excellence.
• Adopt innovative strategies and add on courses in Computer Science and Engineering in
order to meet the national and global changes through student centric learning approach.
• To nurture the excellent and efficient staff and student community along with technical
manpower.
• Establish the state-of-the-art computing system with all modern gadgets for effective
teaching-learning process and research activities.
• Arrange the platform to share the views of the stakeholders to improve the overall
personality development of the students.
• Motivate the social responsibilities of Computer Science Engineers
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.
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
professional engineering practice.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.
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 technological change.
LABORATORY SAFETY RULES
2. Making a noise.
13. Keeping sound levels to a minimum limit that doesn’t disturb others.
GE3171
SYLLABUS
Course Objectives
COURSE OBJECTIVES:
• To understand the problem solving approaches.
• To learn the basic programming constructs in Python.
• To practice various computing strategies for Python-based solutions to real
world problems.
• To use Python data structures - lists, tuples, dictionaries.
• To do input/output with files in Python.
EXPERIMENTS:
Note: The examples suggested in each experiment are only indicative. The lab instructor
is expected to design other problems on similar lines. The Examination shall not be
restricted to the sample experiments listed here.
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)
4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a
library/Components of a car/ Materials required for construction of a building –
operations of list & tuples)
5. Implementing real-time/technical applications using Sets, Dictionaries. (Language,
components of an automobile, Elements of a civil structure, etc.- operations of Sets &
Dictionaries)
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)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.
COURSE OUTCOMES
Ex. Page
Name of the experiment
No. No.
a. Electricity Billing
b. Retail Shop Billing
1. c. Sin Series
d. Weight of a Motorbike
e. Weight of a Steel Bar
Compute Electrical Current in Three Phase AC Circuit
a. Exchange the values of two variables,
a. Number Series
3. b. Number Patterns
c. Pyramid Pattern
a. Factorial of a Number
a.Reversing a String,
9. b. Word count,
c. Longest word
f.
Program No: 1A
Ex. No: DEVELOPING FLOWCHARTS
Date: ELECTRICITY BILLING
Problem Statement:
Start
Read Units
Print Amount
Stop
6
Program No: 1 B
Ex. No:
RETAIL SHOP BILLING
Date:
Problem Statement:
Start
Tax=0.18
Rate_of_item
Display Items
Read Quantities
Cost=Rate_of_item * quantity+
Rate_of_item * quantity+ ……………..
Print BillAmount
Stop
7
Program No: 1C
Ex. No:
SINE SERIES
Date:
Problem Statement:
To evaluate the sine series. The formula used to express the Sin(x) as
Start
Read x, n
x=x*3.14159/180;
t=x;
sum=x;
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
Stop
8
Program No: 1D
Ex. No:
Date: WEIGHT OF A STEEL BAR
Problem Statement:
Start
Read Diameter D
W = D2 / 162
Print W
Stop
9
Program No: 1E
Ex. No: COMPUTE ELECTRICAL CURRENT IN THREE
Date: PHASE AC CIRCUIT
Problem Statement:
Start
VA = * Vline * Aline
Print VA
Stop
10
Aim:
Program:
print("Y= ",y)
x=input("Enter value of X ") #Main Function
y=input("Enter value of Y ")
Output:
Enter value of X: 67
Enter value of Y: 56
Before exchange of
x,y x = 67
Y= 56
After exchange of
x,y x = 56
Y= 67
12
Program No: 2B
Ex. No: CIRCULATE THE VALUES OF N VARIABLES
Date:
Aim:
Program:
def circulate(A,N):
for i in range(1,N+1):
B=A[i:]+A[:i]
print("Circulation ",i,"=",B)
return
A=[91,92,93,94,95]
N=int(input("Enter n:"))
circulate(A,N)
Output:
Enter n:5
Program No: 2C
Ex. No: DISTANCE BETWEEN TWO VARIABLES
Date:
Aim:
To write a python program to find distance between two variables.
Program:
import math
distance = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print("Distance = ",distance)
Output:
Enter a x1: 3
Enter a y1: 2
Enter a x2: 7
Enter a y2: 8
Distance = 7.211102550927978
14
Program No: 3 A
Ex. No: PROGRAMS USING CONDITIONALS AND
ITERATIVE LOOPS
Date: NUMBER SERIES
Aim:
Program:
Output:
Enter a number: 10
Sum = 385
15
Program No: 3 B
Ex. No:
NUMBER PATTERN
Date:
Aim:
To write a python program to print number pattern.
Program:
N=5
for i in range(1,N+1):
for j in range(1,i+1):
for l in range(i−1,0,−1):
print()
Output:
121
12321
1234321
123454321
16
Program No: 3C
Ex. No:
PYRAMID PATTERN
Date:
Aim:
Program:
m = (2 * n) - 2
print(end=" ")
print(" ")
17
Output:
**
***
****
*****
***** *
*******
********
******** *
18
Program No: 4A
Ex. No: OPERATIONS OF LISTS
Date:
Aim:
Program:
library =
['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebooks']
print('Library: ',library)
library.append('Audiobooks')
print('index of \'Newspaper\':
iLIst
library.sort()
library); # popping an
element
library);
# removing specified
element
library.remove('Maps')
Output:
index of 'Newspaper': 2
Program No:4B
Ex. No: OPERATIONS OF TUPLE
Date:
Aim:
Program:
Output:
Program No:5A
Ex. No: OPERATIONS OF SETS
Date:
Aim:
Program:
# set union
# set intersection
# set difference
Output:
Program No:6A
Ex. No: FACTORIAL OF A NUMBER USING FUNCTION
Date:
Aim:
Program:
def fact(n):
if n = = 1:
return n
else:
return n*fact(n−1)
Output:
Enter a number: 5
Program No:6B
Ex. No: FINDING LARGEST NUMBER IN A LIST USING
Date: FUNCTION
Aim:
To write a python program to find the largest number in a list using functions.
Program:
def myMax(list1):
print("Largest element is:", max(list1))
list1 = []
num = int(input("Enter number of elements in list: "))
for i in range(1, num + 1):
ele = int(input("Enter elements: "))
list1.append(ele)
print("Largest element is:", myMax(list1))
Output:
Program No:6C
Ex. No: FINDING AREA OF A CIRCLE USING FUNCTION
Date:
Aim:
Program:
def findArea(r):
PI = 3.142
return PI * (r*r);
num=float(input("Enter r value:"))
print("Area is %.6f" % findArea(num));
Output:
Enter r value:8
Area is 201.088000
27
Program No:7A
Ex. No: REVERSING A STRING
Date:
Aim:
Program:
def reverse(string):
string = "".join(reversed(string))
return string
Output:
Program No:7B
Ex. No: CHECKING PALINDROME IN A STRING
Date:
Aim:
Program:
string = string.casefold()
rev_string = reversed(string)
if list(string) = = list(rev_string):
print("It is palindrome")
else:
Output:
It is not palindrome
29
Program No:7C
Ex. No: COUNTING CHARACTERS IN A STRING
Date:
Aim:
Program:
val = string.count(char)
print(val,"\n")
Output:
2
30
Program No:7D
Ex. No: REPLACE CHARACTERS IN A STRING
Date:
Aim:
Program:
Output:
Step 4:
Program No:8A
Ex. No: PANDAS
Date:
Aim
To write a python program to compare the elements of the two Pandas Series using
Pandas library.
Program:
import pandas as pd
print("Series1:")
print(ds1)
print("Series2:")
print(ds2)
print("Equals:")
print(ds1 == ds2)
print("Greater than:")
print("Less than:")
Output:
Series1:
0 2
1 4
2 6
3 8
4 10
dtype: int64
Series2:
0 1
1 3
2 5
3 7
4 10
dtype: int64
Compare the elements of the said Series:
Equals:
0 False
1 False
2 False
3 False
4 True
dtype: bool
Greater than:
0 True
1 True
2 True
3 True
4 False
dtype: bool
Less than:
0 False
1 False
2 False
3 False
4 False
dtype: bool
36
Program No:8B
Ex. No: NUMPY
Date:
Aim:
To write a program to test whether none of the elements of a given array is zero
using NumPy library.
Program:
import numpy as np
x = np.array([1, 2, 3, 4])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
Output:
Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero:
True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero:
False
37
Program No:8C
Ex. No: MATPLOTLIB
Date:
Aim:
Program:
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
Output:
38
Program No:8D
Ex. No: SCIPY
Date:
Aim:
Program:
print(constants.hour)
print(constants.day)
print(constants.week)
print(constants.year)
print(constants.Julian_year)
Output:
60.0
3600.0
86400.0
604800.0
31536000.0
31557600.0
39
Program No:9A
Ex. No: COPY FROM ONE FILE TO ANOTHER
Date:
Aim:
Program:
Output:
Enter source file name: file1.txt
Enter destination file name: file2.txt
File copied successfully!
Sunflower
Jasmine
Roses
40
Program No:9B
Ex. No: WORD COUNT FROM A FILE
Date:
Aim:
Data.txt
A file is a collection of data stored on a secondary storage device like hard disk. They
can be easily retrieved when required. Python supports two types of files. They are
Text files & Binary files.
Program:
Output:
Program No:9C
Ex. No: FINDING LONGEST WORD IN A FILE
Date:
Aim:
Data.txt
A file is a collection of data stored on a secondary storage device like hard disk. They
can be easily retrieved when required. Python supports two types of files. They are
Text files & Binary files.
Program:
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('F:\Data.txt'))
Output:
['collection']
42
Program No:10A
Ex. No: DIVIDE BY ZERO ERROR USING EXCEPTION
Date: HANDLING
Aim:
To write a python program to handle divide by zero error using exception handling.
Program:
Output:
Program No:10B
Ex. No: VOTERS AGE VALIDITY
Date:
Aim:
Program:
import datetime
Year_of_birth = int(input("In which year you took birth:- "))
current_year = datetime.datetime.now().year
Current_age = current_year - Year_of_birth
print("Your current age is ",Current_age)
if(Current_age<=18):
print("You are not eligible to vote")
else:
print("You are eligible to vote")
Output:
Program No:10C
Ex. No: STUDENT MARK RANGE VALIDATION
Date:
Aim:
Program:
Output:
Program No:11
Ex. No: EXPLORING PYGAME
Date:
PYGAME INSTALLATION
Steps
3. Click
pygame-1.9.3.tar.gz ~ 2M and download zar file
4. Extract the zar file into C:\Python36-32\Scripts folder
5. Open command prompt
6. Type the following command
46
C:\>cd Python36-32\Scripts\pygame-1.9.3
C:\Python36-32\Scripts\pygame-1.9.3>cd
examples
C:\Python36-32\Scripts\pygame-
1.9.3\examples>aliens.py C:\Python36-
32\Scripts\pygame-1.9.3\examples>
54
47
Program No: 12
Ex. No:
SIMULATE ELLIPTICAL ORBITS IN PYGAME
Date:
AIM:
To write a Python program to simulate bouncing ball in Pygame.
ALGORITHM:
1. Start.
2. Import the required packages
3. Set up the colors for the bouncing ball.
4. Define the parameters to simulate bouncing ball.
5. Display the created simulation.
6. Stop.
PROGRAM:
import pygame, sys, time,random
from pygame.locals import*
from time import*
pygame.init()
windowSurface=pygame.display.set_mode((500,400),0,32)
pygame.display.set_caption("BOUNCE")
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
info=pygame.display.Info()
sw=info.current_w
55
sh=info.current_h
y=0
direction=1
while True:
windowSurface.fill(BLACK)
pygame.draw.circle(windowSurface,GREEN,(250,y),13,0)
sleep(.006)
y+=direction
if y>=sh:
direction=-1
elif y<=0:
direction=1
pygame.display.update()
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
OUTPUT:
RESULT:
Thus the Python program to simulate elliptical orbits in Pygame was executed and
verified successfully.
56
57