Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
89 views

Python 140

Uploaded by

Hussain k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views

Python 140

Uploaded by

Hussain k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

PYTHON PROGRAMMING

LAB MANUAL
PARUL UNIVERSITY
FACULTY OF ENGINEERING & TECHNOLOGY PARUL INSTITUTE OF ENGINEERING &
TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING /
INFORMATION TECHNOLOGY

STUDENT DETAILS

NAME : HUSSAIN KAGIWALA


ENROLLMENT NO : 190303108140
SUBJECT : Python Programming Laboratory
SUBJECT CODE : 203105452
SEMESTER : 8th
DIVISION : A1
COURSE : B. Tech IT
FACULTY NAME : Mr. Mohammed Jeeranwala
CERTIFICATE

This is to certify that Mr. HUSSAIN KAGIWALA with enrolment no.

190303108140 has successfully completed his laboratory experiments in the

Python Programming Laboratory (203105452) from the department of

Information Technology during the academic year 2022-2023.

Date of Submission: ......................... Staff In charge: ...........................

Head of Department: ...........................................


INDEX

Marks
Sr. Experiment Title Page Date Sign
(out of
No No
10)
WAP to read and display the following
1 information. Name, Address, Phone no.

WAP to read two numbers from the

2 keyboard and display the larger one on the


screen.

WAP to find, a given number is PRIME


3 or NOT.

Write a Function to swap values of a


pair of integers.
4

WAP to find N! Using function.


5

WAP to print Fibonacci series of ‘n’


numbers, where n is given by the
6 programmer.

WAP to read a set of numbers in an


array & to find the largest of them.
7

WAP to sort a list of names in


8 ascending order.

WAP to read a set of numbers from


keyboard & to find the sum of all
9 elements of the given array using a
function.
Calculate area of different
10 geometrical figures (circle, rectangle,
square, and triangle).
WAP to increment the employee
salaries on the basis of their
designation (Manager-5000,
GeneralManager-10000, CEO-
11
20000, worker-2000). Use employee
name, id, designation and salary as
data member and inc_sal as member
function.
WAP to read data from keyboard &
write it to the file. After writing is
12 completed, the file is closed. The
program again opens the same file
and reads it.
Write a program to implement Bubble
13 Sort Technique.

Write a program to implement Linear


14 Search and Binary Search Technique.

Consider a database table for a Bank


with attributes Account No, Customer
Name, Balance, Phone and Address.
Write a program which allows
15 insertion, updation and deletion of
records in Bank table. Print values of
all customers whose balance is
greater than 20,000.
Create two classes namely Employee
and Qualification. Using multiple
inheritance derive two classes.
16
Scientist and Manager. Take suitable
attributes & operations. WAP to
implement this class hierarchy.
Write a program to draw a shape
17 using turtle.
Write a Python program to create
18 ulti-widget GUI using Tkinter.

Assume that a list of Students“ height


ches is given. Create a Numpy arr
om this list and then multiply that arr
19 ith 0.0254 to convert all heig
easurements into meters and print t
umpy array Height lis
80,215,176,150,181,209]
Implement any one sorting algorith
ing TCP/UDP on Server applicatio
ovide the input on Client side and clie
20 ould receive sorted output from serve
isplay the sorted output on client.
Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

PRACTICAL: 1

Aim: - WAP to read and display the following information. Name, Address,
Phone no.

Program:
name = input("Please enter your name: ")
address = input("Please enter your address: ")
phone = input("Please enter your phone number: ")

print("Name:", name)
print("Address:", address)
print("Phone number:", phone)

Output:

EEnrnrool l m
e ennt N o: :190303108140 Page | 1
Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
PRACTICAL: 2

Aim: - WAP to read two numbers from the keyboard and display the larger
one on the screen.

Program:

# Read the first number


num1 = float(input("Please enter the first number: "))

# Read the second number


num2 = float(input("Please enter the second number: "))

# Determine and display the larger number


if num1 > num2:
print(num1, "is larger")
else:
print(num2, "is larger")

Output:

Enrollment No: 190303108140 Page | 2


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

PRACTICAL: 3

Aim: - WAP to find, a given number is PRIME or NOT.

Program:

num = int(input("Please enter a number: "))

# Check if the number is prime


if num <= 1:
print(num, "is not prime")
else:
for i in range(2, num):
if num % i == 0:
print(num, "is not prime")
break
else:
print(num, "is prime")

Output:

Enrollment No: 190303108140 Page | 3


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
PRACTICAL: 4

Aim: - Write a Function to swap values of a pair of integers.

Program:

def swap(a, b):


a, b = b, a
return (a, b)

x=1
y=2

x, y = swap(x, y)

print("x =", x)
print("y =", y)

Output:

Enrollment No: 190303108140 Page | 4


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
PRACTICAL: 5

Aim: - WAP to find N! Using function.

Program:
def factorial(n):
# Initialize the result to 1
result = 1
# Iterate over the range of integers from 1 to n
for i in range(1, n+1):
# Multiply the result by the current number
result *= i
return result

print(factorial(5))
print(factorial(10))

Output:

Enrollment No: 190303108140 Page | 5


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
PRACTICAL: 6

Aim: - WAP to print Fibonacci series of ‘n’ numbers, where n is given by the
programmer.

Program:

def fibonacci(n):
# Initialize the first two numbers in the series
a, b = 0, 1
# Iterate over the range of integers from 1 to n
for i in range(1, n+1):
print(b)
# Calculate the next number in the series
a, b = b, a+b
n = 10
print("Fibonacci series of", n, "numbers:")
fibonacci(n)

Output:

Enrollment No: 190303108140 Page | 6


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
PRACTICAL: 7

Aim: - WAP to read a set of numbers in an array & to find the largest of them.

Program:
# Read the number of elements in the array
n = int(input("Please enter the number of elements in the array: "))
numbers = []

for i in range(n):
numbers.append(int(input("Please enter element {}: ".format(i+1))))

# Find the largest element in the array


largest = numbers[0]

for number in numbers:


if number > largest:
largest = number

print("The largest element in the array is", largest)

Output:

Enrollment No: 190303108140 Page | 7


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
PRACTICAL: 8

Aim: - WAP to sort a list of names in ascending order.

Program:
n = int(input("Please enter the number of names: "))

names = []

for i in range(n):
names.append(input("Please enter name {}: ".format(i+1)))

names.sort()

print("Sorted names:")
for name in names:
print(name)

Output:

Enrollment No: 190303108140 Page | 8


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
PRACTICAL: 9

Aim: - WAP to read a set of numbers from keyboard & to find the sum of all
elements of the given array using a function.

Program:
def sum_array(numbers):
result = 0
for number in numbers:
result += number
return result

n = int(input("Please enter the number of elements in the array: "))


numbers = []
for i in range(n):
numbers.append(int(input("Please enter element {}: ".format(i+1))))

# Find the sum of the elements of the array


result = sum_array(numbers)
print("The sum of the elements of the array is", result)

Output:

Enrollment No: 190303108140 Page | 9


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
PRACTICAL: 10

Aim: - calculate area of different geometrical figure(circle, rectangle, square


and triangle).

Program:

import random

# Function to calculate the area of a circle


def area_circle(radius):
return 3.14 * radius * radius

# Function to calculate the area of a rectangle


def area_rectangle(length, width):
return length * width

# Function to calculate the area of a square


def area_square(side):
return side * side

# Function to calculate the area of a triangle


def area_triangle(base, height):
return 0.5 * base * height

# Generate random inputs for the different figures


radius = random.uniform(1, 50)
length = random.uniform(1, 50)
width = random.uniform(1, 50)
side = random.uniform(1, 50)
base = random.uniform(1, 50)
height = random.uniform(1, 50)

# Calculate the areas of the different figures


area_c = area_circle(radius)
area_r = area_rectangle(length, width)
area_s = area_square(side)
area_t = area_triangle(base, height)

# Print the areas of the different figures


print("Area of circle:", area_c)
print("Area of rectangle:", area_r)
print("Area of square:", area_s)
print("Area of triangle:", area_t)

Enrollment No: 190303108140 Page | 10


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
Output:

Enrollment No: 190303108140 Page | 11


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

PRACTICAL: 11

Aim: - WAP to increment the employee salaries on the basis of their


designation (Manager-5000, General Manager-10000, CEO-20000, worker-
2000). Use employee name, id, designation and salary as data member and
inc_sal as member function.

Program:
import random
class Employee:
def __init__(self, name, id, designation, salary):
self.name = name
self.id = id
self.designation = designation
self.salary = salary

def inc_sal(self):
if self.designation == "Manager":
self.salary += 5000
elif self.designation == "General Manager":
self.salary += 10000
elif self.designation == "CEO":
self.salary += 20000
elif self.designation == "Worker":
self.salary += 2000

# Generate random inputs for the employees


names = ["Alice", "Bob", "Charlie", "Dave", "Eve"]
ids = [1, 2, 3, 4, 5]
designations = ["Manager", "General Manager", "CEO", "Worker"]
salaries = [10000, 20000, 30000, 40000, 50000]

# Create the employees


employees = []
for i in range(5):
name = random.choice(names)
id = random.choice(ids)
designation = random.choice(designations)
salary = random.choice(salaries)
employees.append(Employee(name, id, designation, salary))

for employee in employees:


employee.inc_sal()

Enrollment No: 190303108140 Page | 12


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
for employee in employees:
print("Employee {} ({}) has a new salary of {}".format(employee.name, employee.id,
employee.salary))

Output:

Enrollment No: 190303108140 Page | 13


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
PRACTICAL: 12

Aim: - WAP to read data from keyboard & write it to the file. After writing is
completed, the file is closed. The program again opens the same file and reads
it.

Program:

data = input("Please enter the data to be written to the file: ")

# Open the file for writing


with open("data.txt", "w") as f:
# Write the data to the file
f.write(data)

# Open the file for reading


with open("data.txt", "r") as f:
# Read and print the data from the file
data = f.read()
print("Data from file:", data)

Output:

Enrollment No: 190303108140 Page | 14


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
PRACTICAL: 13

Aim: - Write a program to implement Bubble Sort Technique.

Program:
def bubble_sort(arr):
for i in range(len(arr)-1):
# Flag to indicate whether any swaps were made
swapped = False
for j in range(len(arr)-1-i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
# If no swaps were made, the array is sorted
if not swapped:
break
return arr

arr = [5, 3, 2, 4, 1]
sorted_arr = bubble_sort(arr)
print(sorted_arr)

Output:

Enrollment No: 190303108140 Page | 15


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

PRACTICAL: 14

Aim: - Write a program to implement Linear Search and Binary Search


Technique.

Program:

def linear_search(arr, target):


for i, element in enumerate(arr):
if element == target:
return i

def binary_search(arr, target):


start = 0
end = len(arr) - 1
while start <= end:
mid = (start + end) // 2
if arr[mid] == target:
return mid
elif target < arr[mid]:
end = mid - 1
else:
start = mid + 1
return -1

# Test the linear_search function


arr = [5, 3, 2, 4, 1]
target = 4
index = linear_search(arr, target)
print("Linear search: target {} found at index {}".format(target, index))

# Test the binary_search function


arr = [1, 2, 3, 4, 5]
target = 4
index = binary_search(arr, target)
print("Binary search: target {} found at index {}".format(target, index))

Enrollment No: 190303108140 Page | 16


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
Output:

Enrollment No: 190303108140 Page | 17


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
PRACTICAL NO: 15

AIM: Consider a database table for a Bank with attributes AccountNo,


CustomerName, Balance, Phone and Address. Write a program which allows
insertion, updation and deletion of records in Bank table. Print values of all
customers whose balance is greater than 20,000.

Code:

import sqlite3
# create a connection to the database
conn = sqlite3.connect('bank.db')

# create a cursor object to execute SQL commands


c = conn.cursor()

# create the Bank table with columns AccountNo, CustomerName, Balance, Phone, and
Address
c.execute('''CREATE TABLE IF NOT EXISTS Bank (
AccountNo INTEGER PRIMARY KEY,
CustomerName TEXT NOT NULL,
Balance REAL NOT NULL,
Phone TEXT NOT NULL,
Address TEXT NOT NULL)''')

# insert a record into the Bank table


def insert_record(account_no, customer_name, balance, phone, address):
c.execute("INSERT INTO Bank (AccountNo, CustomerName, Balance, Phone, Address)
VALUES (?, ?, ?, ?, ?)",
(account_no, customer_name, balance, phone, address))
conn.commit()
# update a record in the Bank table
def update_record(account_no, balance):
c.execute("UPDATE Bank SET Balance = ? WHERE AccountNo = ?", (balance,
account_no))
conn.commit()
# delete a record from the Bank table
def delete_record(account_no):
c.execute("DELETE FROM Bank WHERE AccountNo = ?", (account_no,))
conn.commit()

Enrollment No: 190303108140 Page | 18


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

# print the details of all customers with a balance greater than 20,000
def print_records_with_balance_gt_20000():
c.execute("SELECT * FROM Bank WHERE Balance > 20000")
records = c.fetchall()
for record in records:
print(record)

# insert some records into the Bank table


insert_record(1, 'Alice', 10000.00, '123-456-7890', '123 Main St.')
insert_record(2, 'Bob', 25000.00, '234-567-8901', '456 Elm St.')
insert_record(3, 'Charlie', 5000.00, '345-678-9012', '789 Oak St.')

# update a record in the Bank table


update_record(1, 15000.00)

# delete a record from the Bank table


delete_record(3)

# print the details of all customers with a balance greater than 20,000
print_records_with_balance_gt_20000()

# close the connection to the database


conn.close()

Output:

Conclusion:
In this implementation of practical I have learned how to import sqlite3 and how to work
with database. And I have learned different types of operation on SQLite3.and leaned how to
apply conditions on table data

Enrollment No: 190303108140 Page | 19


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

PRACTICAL NO: 16

AIM: Create two classes namely Employee and Qualification. Using multiple
inheritance derive two classes Scientist and Manager. Take suitableattributes &
operations. WAP to implement this class hierarchy.

Code:

class Employee:
def __init__ (self,name,age):
self.name = name
self.age = age
def employee_details(self):
print('Name is ' ,self.name)
print('Age is ',self.age)
class Qualification:
def __init__ (self,degree,college):
self.degree=degree
self.college=college
def qualification_details(self):
print('Name of degree',self.degree)
print('Name of college',self.college)
class Scientist(Employee,Qualification):
def __init__ (self,name,age,degree,college):
Employee. __init__(self,name,age)
Qualification. __init__ (self,degree,college)
print("Scientist's Details:-")
class Manager(Employee,Qualification):
def __init__ (self,name,age,degree,college):
Employee. __init__(self,name,age)
Qualification. __init__ (self,degree,college)
print('Manager\'s deatils:-')
s1=Scientist('ABC',11,'B.tech- IT','XYZ')
s1.employee_details()
s1.qualification_details()
m1=Manager('ABC',11,'B.tech - IT','XYZ')
m1.employee_details()
m1.qualification_details()

Enrollment No: 190303108140 Page | 20


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

Output:

Conclusion:
In this implementation of practical I have learned how to use of oop concept in python. And I
have learned how to implement inheritance in python with different classes. And how to
create objects in python and how to call class using of this object

Enrollment No: 190303108140 Page | 21


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

PRACTICAL NO: 17

AIM: Write a program to draw a shape using turtle.

Code:

import turtle
def form_tri(side):
for i in range(3):
my_pen.fd(side)
my_pen.left(120)
side -= 10
# window screen
tut = turtle.Screen()
tut.bgcolor("orange")
tut.title("Turtle")
my_pen = turtle.Turtle()
my_pen.color("white")
tut = turtle.Screen()
# different shapes
side = 300
for i in range(10):
form_tri(side)
side -= 30

Output:

Conclusion:
In this implementation of practical I have learned how import turtle libraries and how to
work with this library and how to draw different types of shapes using of turtle.

Enrollment No: 190303108140 Page | 22


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

PRACTICAL NO: 18

AIM: Write a Python program to create multi-widget GUI using Tkinter.

Code:

from tkinter import *


from tkinter.ttk import Combobox
window=Tk()
var = StringVar()
var.set("1year")
data=("1year", "2year", "3year", "4year")
cb=Combobox(window, values=data)
cb.place(x=60, y=150)

lb=Listbox(window, height=5, selectmode='multiple')


for num in data:
lb.insert(END,num)
lb.place(x=250, y=150)

v0=IntVar()
v0.set(1)
r1=Radiobutton(window, text="Male", variable=v0,value=1)
r2=Radiobutton(window, text="Female", variable=v0,value=2)
r1.place(x=100,y=50)
r2.place(x=180, y=50)

v1 = IntVar()
v2 = IntVar()
C1 = Checkbutton(window, text = "Boy", variable = v1)
C2 = Checkbutton(window, text = "Girl", variable = v2)
C1.place(x=100, y=100)
C2.place(x=180, y=100)

window.title('Hello Students')
window.geometry("400x300+10+10")
window.mainloop()

Enrollment No: 190303108140 Page | 23


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

Output:

Conclusion:
In this implementation of practical I have learned how to use tkinter library in Python. Using
of this library I have learned how to implement a radio button, how to implement a Check
box, and How to implement a dropdown list in python.

Enrollment No: 190303108140 Page | 24


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

PRACTICAL NO: 19

AIM: Assume that a list of Students “height in inches is given. Create a Numpy
array from this list and then multiply that array with 0.0254 to convert all height
measurements into meters and print the Numpy array Height_list =
[180,215,176,150,181,209]

Code:

class Student(object):
def __init__ (self, name, height):
self.name = name
self.height = height
def getheight(self):
return self.height
def str (self):
return self.name + ' : ' + str(self.getheight())
def HeightRecord(rec, name, height):
rec.append(Student(name, height))
return rec
Record = [x] = 'y'
while x == 'y':
name = input('Enter the name of the student: ')
height = input('Enter the height recorded: ')
Record = HeightRecord(Record, name, height)
x= input('another student? y/n ')
n=1
for el in Record:
print(n,'. ', el)
n=n+1

Output:

Enrollment No: 190303108140 Page | 25


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

PRACTICAL NO: 20

AIM: Implement any one sorting algorithm using TCP/UDP on Server


application. Provide the input on Client side and client should receive sorted
output from server. Display the sorted output on client.

Code:

Server:

import socket
def binary_search(arr, val, start, end):
if start == end:
if arr[start] > val:
return start
else:
return start + 1
if start > end:
return start

mid = (start + end) // 2


if arr[mid] < val:
return binary_search(arr, val, mid + 1, end)
elif arr[mid] > val:
return binary_search(arr, val, start, mid - 1)
else:
return mid

def binary_insertion_sort(arr):
for i in range(1, len(arr)):
val = arr[i]
j = binary_search(arr, val, 0, i - 1)
arr = arr[:j] + [val] + arr[j:i] + arr[i+1:]
return arr

HOST = 'localhost'
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:


s.bind((HOST, PORT))
s.listen()
print(f'Server listening on {HOST}:{PORT}...')

Enrollment No: 190303108140 Page | 26


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8

while True:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
data = conn.recv(1024)
arr = list(map(int, data.decode().split(',')))
sorted_arr = binary_insertion_sort(arr)
sorted_data = ','.join(map(str, sorted_arr)).encode()
conn.sendall(sorted_data)

Client:

import socket

HOST = 'localhost'
PORT = 65432

def get_input():
while True:
try:
n = int(input("Enter the number of elements to be sorted: "))
if n <= 0:
print("Please enter a positive integer.")
else:
break
except ValueError:
print("Please enter a valid integer.")

arr = []
for i in range(n):
while True:
try:
element = int(input(f"Enter element {i+1}: "))
break
except ValueError:
print("Please enter a valid integer.")
arr.append(element)
return arr

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:


s.connect((HOST, PORT))
arr = get_input()
data = ','.join(map(str, arr)).encode()
s.sendall(data)
sorted_data = s.recv(1024)

Enrollment No: 190303108140 Page | 27


Faculty Of Engineering & Technology
Subject Name: Python Programming
Subject Code: 203105452
B. Tech. IT Year 4rd Semester 8
sorted_arr = list(map(int, sorted_data.decode().split(',')))
print(f'Sorted array received from server: {sorted_arr}')

Output: Server:

Output: Client:

Conclusion:
In this implementation of practical I have learned how to use of socket library and how to
connect with server and how client and server will work in request - response method. And
how to get and put data from client side.

Enrollment No: 190303108140 Page | 28

You might also like