0% found this document useful (0 votes)
12 views57 pages

lab manual (1)

The document is a laboratory manual for the GE3171 Problem Solving and Python Programming course at Bethlehem Institute of Engineering. It outlines the vision, mission, program educational objectives, specific objectives, and outcomes, along with laboratory safety rules and course objectives. Additionally, it includes a syllabus detailing various experiments and programming tasks to be completed by students, focusing on problem-solving using Python.

Uploaded by

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

lab manual (1)

The document is a laboratory manual for the GE3171 Problem Solving and Python Programming course at Bethlehem Institute of Engineering. It outlines the vision, mission, program educational objectives, specific objectives, and outcomes, along with laboratory safety rules and course objectives. Additionally, it includes a syllabus detailing various experiments and programming tasks to be completed by students, focusing on problem-solving using Python.

Uploaded by

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

BETHLAHEM INSTITUTE OF ENGINEERING

NADUTHERI, KARUNGAL – 629 157


(Approved by AICTE,New Delhi 1-3361406901&Affiliated to Anna University,
Chennai)

GE3171
PROBLEM SOLVING AND PYTHON PROGRAMMING
LABORATORY
(LABORATORY MANUAL)

(R-2021)

I SEMESTER

DEPARTMENT OF INFORMATION TECHNOLOGY

Prepared by: S.Akhila Judit Nisha

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

PROGRAM EDUCATIONAL OBJECTIVES (PEOs):


To enable graduates to pursue higher education and research, or have a successful career
in industries associated with Computer Science and Engineering, or as entrepreneurs. To ensure
that graduates will have the ability and attitude to adapt to emerging technological changes.

PROGRAM SPECIFIC OBJECTIVES (PSOs)

• To analyze, design and develop computing solutions by applying foundational


concepts of Computer Science and Engineering.
• To apply software engineering principles and practices for developing quality
software for scientific and business applications.
• To adapt to emerging Information and Communication Technologies (ICT)
to innovate ideas and solutions to existing/novel problems.
PROGRAMME OUTCOMES (POs)
Program outcomes

Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.

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.

4. Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

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.

7. Environment and sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

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.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive clear
instructions.

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

Students should not involve in below mentioned activities in the lab


1. Eating and drinking.

2. Making a noise.

3. Downloading data without authorization.

4. Installing personal software on computers including games.

5. Copy or transfer any software data.

6. Plugging a personal USB/Card/CD or any other device into the computers.

7. Interfering with or disturbing other students.

8. Propagating computer viruses, spamming and offensive material.

9. Tampering with, attempting to repair, or misusing the lab equipment.

10. Bringing mobile phones and other multimedia devices.

11. Writing on tables/computers.

12. Viewing unwanted material, etc.

13. Keeping sound levels to a minimum limit that doesn’t disturb others.
GE3171

PROBLEM SOLVING AND PYTHON PROGRAMMING


LABORATORY

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

• Develop simple algoithms.

• Develop and implement simple python programs..

•Develop python programs using conditional and looping statements.

• Develop simple python .programs using functions.


• Use Python packages in simple programs.

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,

2. b. Circulate the values of n variables,


c. Distance between two points.

a. Number Series

3. b. Number Patterns
c. Pyramid Pattern

1. Operations of Lists and Tuples (Items present in a


library/Components of a car/ Materials required for
4.
construction of a building)
1. Operations of Sets & Dictionaries (Language,
components of an automobile, Elements of a civil
5.
structure, etc)

a. Factorial of a Number

6. b. Largest Number in a list


c. Area of Shape

a.Reversing a String,

b.Checking Palindrome in a String


7.
c.Counting Characters in a String

d.Replacing Characters in a String

1. Programs Using modules and Python Standard Libraries


8. (pandas, numpy. Matplotlib, scipy)

a. Copy from one file to another,

9. b. Word count,
c. Longest word

a. Divide by zero error,

10. b. Voter’s age validity,


c. Student mark range validation

d. Exploring Pygame tool.


11.
e.
1. Developing a game activity using Pygame like bouncing ball,
12. car race etc.

f.
Program No: 1A
Ex. No: DEVELOPING FLOWCHARTS
Date: ELECTRICITY BILLING

Problem Statement:

• For 0 to 100 units the per unit is ₹ 0/-


• For 0 to 200 units, for the first 100 unit the per unit cost is zero and the next
100 units, the consumer shall pay ₹ 1.5 per unit.
• For 0 to 500 units, the consumer shall pay ₹ 0 for the first 100 units, for the
next 100 units the consumer shall pay ₹ 2 per unit, for the next 300 units the
unit cost is ₹3.00/-
• For above 500 units, the consumer shall pay ₹ 0 for the first 100 units, for
the next 100 units the consumer shall pay ₹ 3.50 per unit, for the next 300
units the unit cost is ₹4.60/- and for the remaining units the unit cost is
₹6.60/-
5

Start

Read Units

<=100 <=200 Unit <= 500 >500


s
=
?

Amount Amount = (100* Amount = (100*


Amount = (100*
= 100* 0) + (Unit – 0) + (200 –
0) + (200–
0 100)*1.5 100)*3.5 + (500
100)*2 +
– 200)* 4.6+
(Unit – 200)*3
(Unit – 500) * 6.6

Print Amount

Stop
6

Program No: 1 B
Ex. No:
RETAIL SHOP BILLING
Date:

Problem Statement:

To prepare Retail shop billing flowchart.

Start

Tax=0.18
Rate_of_item

Display Items

Read Quantities

Cost=Rate_of_item * quantity+
Rate_of_item * quantity+ ……………..

BillAmount = cost + cost * tax

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;

i=1; i <=n; i++

t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;

Print sum as sine(x)

Stop
8

Program No: 1D
Ex. No:
Date: WEIGHT OF A STEEL BAR

Problem Statement:

To find the weight of a steel bar.

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:

To compute electrical current in three phase AC circuit.

Start

Read Vline , Aline

VA = * Vline * Aline

Print VA

Stop
10

Program No: 2 A PROGRAMS USING SIMPLE STATEMENTS


Ex. No:
EXCHANGE THE VALUES OF TWO VARIABLES
Date:

Aim:

To write a python program to exchange the values of two variables.

Program:

def exchange(x,y): #Function Definition


x,y=y,x # swapping using tuple assignment
print("After exchange of x,y")
print("x =",x)

print("Y= ",y)
x=input("Enter value of X ") #Main Function
y=input("Enter value of Y ")

print("Before exchange of x,y")


print("x =",x)
print("Y= ",y)
exchange(x,y) # Function call
11

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:

To write a python program to calculate the values of N variables.

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

Circulation 1 = [92, 93, 94, 95, 91]

Circulation 2 = [93, 94, 95, 91, 92]

Circulation 3 = [94, 95, 91, 92, 93]

Circulation 4 = [95, 91, 92, 93, 94]

Circulation 5 = [91, 92, 93, 94, 95]


13

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

x1 = int(input("Enter a x1: "))

y1 = int(input("Enter a y1: "))

x2 = int(input("Enter a x2: "))

y2 = int(input("Enter a y2: "))

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:

To write a python program to evaluate 12+22+32+….+N2

Program:

n = int(input('Enter a number: '))


sum=0
i=1
while i<=n:
sum=sum+i*i
i+=1
print('Sum = ',sum)

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 k in range(N,i, –1):

print(" ", end =' ')

for j in range(1,i+1):

print(j, end =' ')

for l in range(i−1,0,−1):

print(l, end =' ')

print()

Output:

121

12321

1234321

123454321
16

Program No: 3C
Ex. No:
PYRAMID PATTERN
Date:

Aim:

To write a python program to print number pattern.

Program:

n = int(input("Enter the number of rows: "))

m = (2 * n) - 2

for i in range(0, n):

for j in range(0, m):

print(end=" ")

m = m - 1 # decrementing m after each loop

for j in range(0, i + 1):

# printing full Triangle pyramid using stars

print("* ", end=' ')

print(" ")
17

Output:

Enter the number of rows: 9

**

***

****

*****

***** *

*******

********

******** *
18

Program No: 4A
Ex. No: OPERATIONS OF LISTS
Date:

Aim:

To Implement operations in a library list.

Program:

# declaring a list of items in a Library

library =
['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebooks']

# printing the complete list

print('Library: ',library)

# printing first element

print('first element: ',library[0])

# printing fourth element

print('fourth element: ',library[3])

# printing list elements from 0th index to 4th index

print('Items in Library from 0 to 4 index: ',library[0: 5])

# printing list -7th or 3rd element from the list

print('3rd or -7th element: ',library[-7])

# appending an element to the list

library.append('Audiobooks')

print('Library list after append(): ',library)


19

# finding index of a specified element

print('index of \'Newspaper\':

',library.index('Newspaper')) # sorting the elements of

iLIst

library.sort()

print('after sorting: ',

library); # popping an

element

print('Popped elements is:

',library.pop()) print('after pop(): ',

library);

# removing specified

element

library.remove('Maps')

print('after removing \'Maps\':

',library) # inserting an element at

specified index # inserting 100 at

2nd index library.insert(2, 'CDs')

print('after insert: ', library)

# Number of Ekements in Library list

print(' Number of Elements in Library list : ',library.count('Ebooks'))

Output:

Library: ['Books', 'Periodicals', 'Newspaper', 'Manuscripts', 'Maps',


'Prints', 'Documents', 'Ebooks']

first element: Books

fourth element: Manuscripts


20

Items in Library from 0 to 4 index: ['Books', 'Periodicals',


'Newspaper', 'Manuscripts', 'Maps']

3rd or -7th element: Periodicals

Library list after append(): ['Books', 'Periodicals', 'Newspaper',


'Manuscripts', 'Maps', 'Prints', 'Documents', 'Ebooks', 'Audiobooks']

index of 'Newspaper': 2

after sorting: ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts',


'Maps', 'Newspaper', 'Periodicals', 'Prints']

Popped elements is: Prints

after pop(): ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts',


'Maps', 'Newspaper', 'Periodicals']

after removing 'Maps': ['Audiobooks', 'Books', 'Documents',


'Ebooks', 'Manuscripts', 'Newspaper', 'Periodicals']

after insert: ['Audiobooks', 'Books', 'CDs', 'Documents', 'Ebooks',


'Manuscripts', 'Newspaper', 'Periodicals']

Number of Elements in Library list : 1


21

Program No:4B
Ex. No: OPERATIONS OF TUPLE
Date:

Aim:

To Implement operations in a Car Tuple.

Program:

# Python code for various Tuple operation

# declaring a tuple of Components of a car


car = ('Engine','Battery','Alternator','Radiator','Steering','Break','Seat Belt')

# printing the complete tuple


print('Components of a car: ',car)

# printing first element


print('first element: ',car[0])

# printing fourth element


print('fourth element: ',car[3])

# printing tuple elements from 0th index to 4th index


print('Components of a car from 0 to 4 index: ',car[0: 5])

# printing tuple -7th or 3rd element from the list


print('3rd or -7th element: ',car[-7])
22

# finding index of a specified element


print('index of \'Alternator\': ',car.index('Alternator'))

# Number of Elements in car tuple


print(' Number of Elements in Car Tuple : ',car.count('Seat Belt'))

#Length of car tuple


print(' Length of Elements in Car Tuple : ',len(car))

Output:

Components of a car: ('Engine', 'Battery', 'Alternator', 'Radiator', 'Steering',


'Break', 'Seat Belt')
first element : Engine
fourth element :
Radiator
Components of a car from 0 to 4 index: ('Engine', 'Battery', 'Alternator',
'Radiator', 'Steering')
3rd or -7th element:
Engine index of
'Alternator': 2
Number of Elements in Car Tuple :
1
Length of Elements in Car Tuple :
7
23

Program No:5A
Ex. No: OPERATIONS OF SETS
Date:

Aim:

To Implement operations in a set using Components of a Language as example.

Program:

L1 = {'Pitch', 'Syllabus', 'Script', 'Grammar', 'Sentences'};

L2 = {'Grammar', 'Syllabus', 'Context', 'Words', 'Phonetics'};

# set union

print("Union of L1 and L2 is ",L1 | L2)

# set intersection

print("Intersection of L1 and L2 is ",L1 & L2)

# set difference

print("Difference of L1 and L2 is ",L1 - L2)

# set symmetric difference

print("Symmetric difference of L1 and L2 is ",L1 ^ L2)

Output:

Union of L1 and L2 is {'Words', 'Pitch', 'Sentences', 'Phonetics', 'Script', 'Grammar',


'Syllabus', 'Context'}
Intersection of L1 and L2 is {'Grammar', 'Syllabus'}
Difference of L1 and L2 is {'Script', 'Pitch', 'Sentences'}
Symmetric difference of L1 and L2 is {'Words', 'Context', 'Script', 'Pitch',
'Sentences', 'Phonetics'}
24

Program No:6A
Ex. No: FACTORIAL OF A NUMBER USING FUNCTION
Date:

Aim:

To write a python program to find the factorial of a number using functions.

Program:

def fact(n):

if n = = 1:

return n

else:

return n*fact(n−1)

num = int(input("Enter a number: "))

print("The factorial of",num,"is",fact(num))

Output:

Enter a number: 5

The factorial of 5 is 120


25

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:

Enter number of elements in list: 6


Enter elements: 58
Enter elements: 69
Enter elements: 25
Enter elements: 37
Enter elements: 28
Enter elements: 49
Largest element is: 69
26

Program No:6C
Ex. No: FINDING AREA OF A CIRCLE USING FUNCTION
Date:

Aim:

To write a python program to find the area of a circle using functions.

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:

To write a python program to reverse a string.

Program:

def reverse(string):
string = "".join(reversed(string))
return string

s = input("Enter any string: ")


print ("The original string is : ",end="")
print (s)

print ("The reversed string(using reversed) is : ",end="")


print (reverse(s))

Output:

Enter any string: Python


The original string is : Python
The reversed string(using reversed) is : nohtyP
28

Program No:7B
Ex. No: CHECKING PALINDROME IN A STRING
Date:

Aim:

To write a python program to check palindrome in a string.

Program:

string = input("Enter string: ")

string = string.casefold()

rev_string = reversed(string)

if list(string) = = list(rev_string):

print("It is palindrome")

else:

print("It is not palindrome")

Output:

Enter string: Python

It is not palindrome
29

Program No:7C
Ex. No: COUNTING CHARACTERS IN A STRING
Date:

Aim:

To write a python program to count number of characters in a string.

Program:

string = input("Enter any string: ")

char = input("Enter a character to count: ")

val = string.count(char)

print(val,"\n")

Output:

Enter any string: python programming

Enter a character to count: n

2
30

Program No:7D
Ex. No: REPLACE CHARACTERS IN A STRING
Date:

Aim:

To write a python program to replace characters in a string.

Program:

string = input("Enter any string:


") str1 = input("Enter old string:
") str2 = input("Enter new
string: ")
print(string.replace(str1, str2))

Output:

Enter any string: problem solving python


programming Enter old string: python
Enter new string: C
problem solving C programming
INSTALLING AND EXECUTING PYTHON
PROGRAM IN ANACONDA NAVIGATOR
(To run pandas, numpy,matplotlib, scipy)
31

Step 1: Install anaconda individual edition for windows

Step 2: Open Anaconda navigator

Step 3: launch jupyter note book


32

Step 4:

Click new Python3


33

Step 5: Write or paste the python code

Step 6 : click run


34

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.

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

Program:

import pandas as pd

ds1 = pd.Series([2, 4, 6, 8, 10])

ds2 = pd.Series([1, 3, 5, 7, 10])

print("Series1:")

print(ds1)

print("Series2:")

print(ds2)

print("Compare the elements of the said Series:")

print("Equals:")

print(ds1 == ds2)

print("Greater than:")

print(ds1 > ds2)

print("Less than:")

print(ds1 < ds2)


35

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:

To write a python program to plot a graph using matplotlib library.

Program:

import matplotlib.pyplot as plt

import numpy as np

xpoints = np.array([0, 6])

ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)

plt.show()

Output:
38

Program No:8D
Ex. No: SCIPY
Date:

Aim:

To write a python program to return the specified unit


in seconds (e.g. hour returns 3600.0) using scipy library.

Program:

from scipy import constants


print(constants.minute)

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:

To write a python program to copy from one file to another.

Program:

from shutil import copyfile


sourcefile = input("Enter source file name: ")
destinationfile = input("Enter destination file name: ")
copyfile(sourcefile, destinationfile)
print("File copied successfully!")
c = open(destinationfile, "r")
print(c.read())
c.close()
print()
print()

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:

To write a python program to count number of words in a file.

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:

file = open("F:\Data.txt", "rt")


data = file.read()
words = data.split()

print('Number of words in text file :', len(words))

Output:

Number of words in text file : 36


41

Program No:9C
Ex. No: FINDING LONGEST WORD IN A FILE
Date:

Aim:

To write a python program to find longest word in a file.

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:

n=int(input("Enter the value of n:"))


d=int(input("Enter the value of d:"))
c=int(input("Enter the value of c:"))
try:
q=n/(d-c)
print("Quotient:",q)
except ZeroDivisionError:
print("Division by Zero!")

Output:

Enter the value of n:10


Enter the value of d:5
Enter the value of c:5
Division by Zero!
43

Program No:10B
Ex. No: VOTERS AGE VALIDITY
Date:

Aim:

To write a python program to check voters age validity.

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:

In which year you took birth:- 1981


Your current age is 40
You are eligible to vote

In which year you took birth:- 2011


Your current age is 10
You are not eligible to vote
44

Program No:10C
Ex. No: STUDENT MARK RANGE VALIDATION
Date:

Aim:

To write a python program to perform student mark range validation.

Program:

Mark = int(input("Enter the Mark: "))


if Mark < 0 or Mark > 100:
print("The value is out of range, try again.")
else:
print("The Mark is in the range")

Output:

Enter the Mark: 150


The value is out of range, try again.

Enter the Mark: 98


The Mark is in the range
45

Program No:11
Ex. No: EXPLORING PYGAME
Date:

PYGAME INSTALLATION

To Install Pygame Module

Steps

1. Install python 3.6.2 into C:\


2. Go to this link to install pygame www.pygame.org/download.shtml

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:\>py -m pip install pygame


--user Collecting pygame
Downloading pygame-1.9.3-cp36-cp36m-win32.whl (4.0MB)

100% |████████████████████████████████| 4.0MB


171kB/s

Installing collected packages:


pygame Successfully installed
pygame-1.9.3
7. Now, pygame installed successfully
8. To see if it works, run one of the included examples in pygame-1.9.3

• Open command prompt


• Type the following

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

You might also like