0% found this document useful (0 votes)
26 views33 pages

Pyhton Lab Manual Merged

Uploaded by

kanimozhi sekar
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)
26 views33 pages

Pyhton Lab Manual Merged

Uploaded by

kanimozhi sekar
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/ 33

JERUSALEM COLLEGE OF ENGINEERING

(An Autonomous Institution)


(Approved by AICTE, Affiliated to Anna University,
Accredited by NBA and NAAC with ‘A’ Grade)
Velachery Main Road, Narayanapuram, Pallikaranai, Chennai – 600100

JGE1211 PYTHON PROGRAMMING LABORATORY

RECORD NOTEBOOK
ACADEMIC YEAR: 2020 - 2021

I YEAR / II SEM

REGULATION: JCE 2019


DEPARTMENT OF INFORMATION TECHNOLOGY

VISION OF THE DEPARTMENT

Department of Information Technology strives to provide quality education, academic


excellence based on ethical and societal values, exposing students to all concepts, so as to
promote global competitiveness in higher education, multi-disciplinary research and
entrepreneurship.

MISSION OF THE DEPARTMENT

 To attain academic excellence through innovative practices in teaching and research


methodologies.
 To produce globally competent information technologists and entrepreneurs.
 To motivate students to pursue higher education interlaced with communication skills leading
to lifelong learning and societal transformations.
 To provide excellence in multi-disciplinary research and development activities rooted in
ethical and moral values.

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO1 : To ensure graduates will be proficient in utilizing the fundamental knowledge of basic
sciences, mathematics and Information Technology for the applications relevant to various
streams of Engineering and Technology.

PEO2 : To enrich graduates with the core competencies necessary for applying knowledge of
computers and telecommunications equipment to store, retrieve, transmit, manipulate and
analyze data in the context of business enterprise.

PEO3 : To enable graduates to think logically, pursue lifelong learning and will have the capacity to
understand technical issues related to computing systems and to design optimal solutions.

PEO4 : To enable graduates to develop hardware and software systems by understanding the
importance of social, business and environmental needs in the human context.

PEO5 : To enable graduates to gain employment in organizations and establish themselves as


professionals by applying their technical skills to solve real world problems and meet the
diversified needs of industry, academia and research.

PROGRAM SPECIFIC OBJECTIVES (PSOs)

PSO-I : Proficiency to effectively integrate IT-based solutions for contemporary cross-functional


applications.
PSO-II: Ability to analyze, design, implement and evaluate the information systems with ethics, to
meet the local and global requirements for scientific and industry solutions.
JERUSALEM COLLEGE OF ENGINEERING
(An Autonomous Institution)
(Approved by AICTE, Affiliated to Anna University,
Accredited by NBA and NAAC with ‘A’ Grade)
Velachery Main Road, Narayanapuram, Pallikaranai, Chennai - 600100

Name…………………………………………………………………………………………..

Year…………………………………Semester………………Branch……………….

Regulation: …………………………

Register No.

Certified that this is a Bonafide Record work done by the above student in the ………………..

…..……………………………………………………… Laboratory during the year 2020 - 2021.

Signature of Lab. In charge Signature of Head of the Dept.

EXAMINERS

DATE:

INTERNAL EXAMINER EXTERNAL EXAMINER


SYLLABUS
OBJECTIVES:

The student should be made:

 To write, test, and debug simple Python programs.


 To implement Python programs with conditionals and loops.
 Use functions for structuring Python programs.
 Represent compound data using Python lists, tuples, dictionaries.
 To implement basic 2D diagrams.

S. No. NAME OF EXPERIMENT

1 Compute the GCD of two numbers.


2 Find the square root of a number (Newton‘s method)
3 Exponentiation (power of a number)

4 Find the maximum of a list of numbers


5 Guess an integer number in a rang
6 Insert a card in a list of sorted cards.

7 Multiply matrices
8 Programs that take command line arguments (word count)
9 Find the most frequent words in a text read from a file

10 Create an User defined Exception


11 Draw a 2d circle and square
INDEX

Page Signature
S.No Date Name of the Experiment Marks
No. with Date

Average Marks:

Signature:
JGE1211-Python Programming Laboratory

Ex. No: 1

Date:
COMPUTE THE GCD OF TWO NUMBERS

AIM:

To compute the GCD of two numbers

ALGORITHM:

1. Read two input values using input function

2. Convert them into integers

3. Compute GCD using the following steps

a. Find smallest among two inputs

b. Set the smallest

c. Divideboth inputs by the numbers from 1 to smallest+1 If

the remainders of both divisions are zero

Assign that number to gcd

4. Display the GCD

PROGRAM :

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

1
JGE1211-Python Programming Laboratory

if num1 < num2 :

smaller = num1

else:

smaller = num2

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

if (num1 % i == 0) and (num2 % i == 0) :

gcd = i

print("The G.C.D. of ", num1," and ", num2," is = ", gcd)

OUTPUT:

RESULT:

Thus, the program to compute the GCD of two numbers has been executed

successfully.

2
JGE1211-Python Programming Laboratory

Ex. No: 2
FIND THE SQUARE ROOT OF A NUMBER (NEWTON’S
Date: METHOD)

AIM:

To find the square root of a number (Newton’s method)

ALGORITHM:

1. Define a function named newtonSqrt().

2. Initialize approx as 0.5*n and better as 0.5*(approx.+n/approx.)

3. Use a while loop with a condition better!=approx to perform the

following,

i. Set approx.=better ii. Better=0.5*(approx.+n/approx.)

4. Print the value of approx

PROGRAM :

def newtonSqrt(n):

approx = 0.5 * n

better = 0.5 * (approx + n/approx)

while better != approx:

approx = better

better = 0.5 * (approx + n/approx)

return approx

3
JGE1211-Python Programming Laboratory

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

print('The square root is' ,newtonSqrt(n))

OUTPUT:

RESULT:

Thus, the program to To find the square root of a number (Newton’s

method) has been executed successfully.

4
JGE1211-Python Programming Laboratory

Ex. No: 3
EXPONENTIATION (POWER OF A NUMBER)
Date:

AIM:

To write a python program to find exponentiation (power of a Number)

ALGORITHM:

1. Create a functio n using def

2. Check if expone nt value

a. If exponent == 1 Return base value

Else

b. Recursively call the function with (base, exponent-1)

Multiply the result returned by each recursive call with base

value and Return the final result

3. Read base & exponent values using input function

4. Call the function & Print the Result

PROGRAM:

def power(base,exp):

if exp==1:

return(base)

5
JGE1211-Python Programming Laboratory

if exp!=1:

return(base*power(base,exp-1))

base=int(input("Enter base: "))

exp=int(input("Enter exponential value: "))

print("Result:",power(base,exp))

OUTPUT:

RESULT:

Thus, the program to find exponentiation (power of a Number) is executed

successfully

6
JGE1211-Python Programming Laboratory

Ex. No:4
FIND THE MAXIMUM OF A LIST OF NUMBERS
Date:

AIM:

To write a python program to find Maximum of a List of Number

ALGORITHM:

1. Initialize a List

2. Read the Number of Elements

3. Read the List values one by one

4. Set Max = first element of the list

5. Compare Max with List elements

6. If Max< List element

7. Set Max= List element

8. Continue the step 5 until reach the end of the List

9. Print the Max

PROGRAM :

def MaxList():

list1=[]

N=int(input("Enter Number of Values"))

7
JGE1211-Python Programming Laboratory

for i in range (0,N):

x=int(input("Enter a Value"))

list1.append(x)

print(list1)

Max=list1[0]

j=1

while j<N:

if list1[j]>Max :

Max=list1[j]

j=j+1

print(" The Maximum Element in the List is ",Max)

MaxList()

OUTPUT:

RESULT:

Thus, the program to find Maximum of a List of Numbers is executed

successfully

8
JGE1211-Python Programming Laboratory

Ex. No:5
GUESS AN INTEGER NUMBER IN A GIVEN RANGE
Date:

AIM :

To write a python program to guess an integer number within a given

range

ALGORITHM:

1. Import the library random .

2. Get the range within which the number is to be guessed .

3. Use random.randint() function to generate a random number.

4. Ask the user to guess the number correctly.

5. Loop till the number is correctly guessed.

PROGRAM:

import random

lower_limit=int(input("Enter the starting range "))

higher_limit=int(input("Enter the ending range "))

num = random.randint(lower_limit,higher_limit)

while True:

print("Guess a number between",lower_limit," and ",higher_limit,)

guess = input()

9
JGE1211-Python Programming Laboratory

i = int(guess)

if i == num:

print('You won!!!')

break

elif i < num:

print('Try Higher')

elif i > num:

print('Try Lower')

OUTPUT:

10
JGE1211-Python Programming Laboratory

RESULT:

Thus, the program to guess an integer number in a given range is executed

successfully

11
JGE1211-Python Programming Laboratory

Ex. No: 6
INSERT A CARD IN A LIST OF SORTED CARDS
Date:

AIM:

To write a python program to insert a card in a list of sorted cards

ALGORITHM:

1. Define a function to insert the element in the correct position

2. Search for the position of insertion in the sorted list

3. When found split the list using the slice list option

4. Now create a new list by merging the three list that is the two

sliced list and the element to be inserted

PROGRAM :

# Python3 program to insert

# an element into sorted list

# Function to insert element

def insert(list, n):

# Searching for the position

for i in range(len(list)):

if list[i] > n:

index = i

12
JGE1211-Python Programming Laboratory

break

# Inserting n in the list

# list = list[:i] creates new list from from start to pre-defined point

# list = list[i:] creates new list from from pre-defined point to end

list = list[:i] + [n] + list[i:]

return list

# Driver function

list = [1, 2, 4]

n=3

print(insert(list, n))

OUTPUT:

RESULT:

Thus, the Binary Search has been performed successfully

13
JGE1211-Python Programming Laboratory

Ex. No: 7
MULTIPLICATION OF TWO MATRICE
Date:

AIM:

To write a python program to multiply two matrices

ALGORITHM:

1. Create two lists with nested index

2. Initialize an empty list

3. Multiply two matrices

4. Store the results into empty list

5. Display the result

PROGRAM:

A basic code for matrix input from user

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

C = int(input("Enter the number of columns:"))

# Initialize matrix

matrix1= []

matrix2= []

rmatrix= []

print("Enter the entries rowwise for matrix 1:")

14
JGE1211-Python Programming Laboratory

# For user input

for i in range(R): # A for loop for row entries

a =[]

for j in range(C): # A for loop for column entries

a.append(int(input()))

matrix1.append(a)

print("Enter the entries rowwise for matrix 2:")

# For user input

for i in range(R): # A for loop for row entries

a =[]

for j in range(C): # A for loop for column entries

a.append(int(input()))

matrix2.append(a)

print("Creating result matrix with initial zeros ")

# For user input

for i in range(R): # A for loop for row entries

a =[]

for j in range(C): # A for loop for column entries

a.append(int(0))

15
JGE1211-Python Programming Laboratory

rmatrix.append(a)

for i in range(len(matrix1)):

for j in range(len(matrix2[0])):

for k in range(len(matrix2)):

rmatrix[i][j] += matrix1[i][k] * matrix2[k][j]

for r in rmatrix:

print(r)

OUTPUT

16
JGE1211-Python Programming Laboratory

RESULT:

Thus, the program to multiply two matrices has been executed

successfully

17
JGE1211-Python Programming Laboratory

Ex. No: 8
WORD COUNT USING COMMAND LINE ARGUMENTS
Date:

AIM:

To write a python program to implement word count using command line

arguments

ALGORITHM:

1. Import the Sys module.

2. If less than 2 arguments are given, error will be generated.

3. Define functions count_words and count_lines.

4. Split the characters in the file into words and count the number of

words.

5. Split the words if new lines is found and count the number of lines.

6. Return the number of words and number of lines in the file.

PROGRAM:

import sys

if len(sys.argv) < 2:

print("Usage: python word_count.py <file>")

exit(1)

18
JGE1211-Python Programming Laboratory

def count_words(data):

words = data.split(" ")

num_words = len(words)

return num_words

def count_lines(data):

lines = data.split("\n")

for l in lines:

if not l:

lines.remove(l)

return len(lines)

filename = sys.argv[1]

f = open(filename, "r")

data = f.read()

f.close()

num_words = count_words(data)

num_lines = count_lines(data)

print("The number of words: ", num_words+num_lines-1)

print("The number of lines: ", num_lines)

19
JGE1211-Python Programming Laboratory

To run the program

● save the program in a file named Sample.py

● create a text file with any content and save it as data1.txt

● In the terminal type

$ python sample.py data1.txt

OUTPUT

RESULT:

Thus, the program to implement word count using command line

arguments has been executed successfully.

20
JGE1211-Python Programming Laboratory

Ex. No: 9
FIND THE MOST FREQUENT WORDS IN A TEXT
Date: READ FROM A FILE

AIM:

To write a python program to find most frequent words from a given file

ALGORITHM

1. Create a text file and save it as “test.txt”.

2. store the text file in a string variable text_string.

3. In order to apply regular expression easier, turn all the letters in the

document into lower case letters, using thelower() function

4. write regular expressions that would return all the words with the number

of characters in the range [3-15].

5. Use here is Python's Dictionaries, since we need key-value pairs, where key

is the word, and the value represents the frequency words appeared in the

document. Assuming we have declared an empty dictionary frequency = { }

6. Finally,we get the word and its frequency (number of times it appeared in

the text file).

PROGRAM:

import re

import string

21
JGE1211-Python Programming Laboratory

frequency = {}

document_text = open('data.txt', 'r')

text_string = document_text.read().lower()

match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)

for word in match_pattern:

count = frequency.get(word,0)

frequency[word] = count + 1

frequency_list = frequency.keys()

for words in frequency_list:

print(words, frequency[words])

OUTPUT

RESULT:

Thus, the program to find most frequent words was implemented

using python.

22
JGE1211-Python Programming Laboratory

Ex. No: 10
CREATE A USER DEFINED EXCEPTION
Date:

AIM:

To write a python program to create an user defined exception.

ALGORITHM

1. Create user-defined or custom exceptions by creating a new exception

class in Python.

2. Derive the custom exception class “CustomException“ from the exception

class

3. Enter an alphabet again and again ,EXCEPTION IS RAISED when he wrong

alphabet is entered

4. When the correct alphabet is entered the program quits.

PROGRAM

class CustomException(Exception):

"""Base class for other exceptions"""

pass

class PrecedingLetterError(CustomException):

23
JGE1211-Python Programming Laboratory

"""Raised when the entered alphabet is smaller than the actual one"""

pass

class SucceedingLetterError(CustomException):

"""Raised when the entered alphabet is larger than the actual one"""

pass

# we need to guess this alphabet till we get it right

alphabet = 'k'

while True:

try:

foo = input ( "Enter an alphabet: " )

if foo < alphabet:

raise PrecedingLetterError

elif foo > alphabet:

raise SucceedingLetterError

break

except PrecedingLetterError:

print("The entered alphabet is preceding one, try again!")

print('')

except SucceedingLetterError:

print("The entered alphabet is succeeding one, try again!")

print('')

print("Congratulations! You guessed it correctly.")

24
JGE1211-Python Programming Laboratory

OUTPUT

# PROGRAM 2

# define Python user-defined exceptions

class Error(Exception):

"""Base class for other exceptions"""

pass

class Dividebyzero(Error):

"""Raised when the input value is zero"""

pass

25
JGE1211-Python Programming Laboratory

try:

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

if i_num ==0:

raise Dividebyzero

except Dividebyzero:

print("Input value is zero, try again!")

print()

OUTPUT

RESULT:

Thus an user defined exception was created using Python

26
JGE1211-Python Programming Laboratory

Ex. No:11
DRAW A 2D CIRCLE AND SQUARE
Date:

AIM:

To write a python program to draw a circle and a square..

ALGORITHM

1. Import the library turtle

2. create a turtle object

3. get the radius value and use the function circle() to draw the circle

4. move to the given coordinates on screen using goto() func

5. use the combinations of forward() func and left() func functions to draw a

square

PROGRAM:

import turtle

R = int(input("Enter the radius of the circle "))

t = turtle.Turtle()

t.color("red")

t.circle(R)

turtle.color("purple")

D = int(input("Enter the Dimension of the square "))

27
JGE1211-Python Programming Laboratory

turtle.penup()

turtle.goto(200,0)

turtle.pendown()

turtle.forward(D)

turtle.left(90)

turtle.forward(D)

turtle.left(90)

turtle.forward(D)

turtle.left(90)

turtle.forward(D)

turtle.left(90)

OUTPUT

Result:

Thus a circle and square were drawn using Python

28

You might also like