You are on page 1of 50

SubCode: 18CS5SP08L

Name : M.Sai Nikhil


Usn : 18BTRCE020
Sub: IT Workshop-Python
LAB EXPERIMENTS

1. Write and run a program

a. To elaborate variables and their data types such as int, float,


boolean, string, list, set, dictionary and tuples; exchange of
two values.

b. To elaborate mathematical operations such as addition,


subtraction, multiplication, division, modulo, and power; also
explore the operator precedence.
Experiment-2

a. Python program to find the sum and average of


natural numbers up to n where n is provided by user.

#Program

print("Name : sai nikhil \nUsn : 18BTRCE020")


n = int(input("please enter number of terms to find
sum and average"))
sum = 0
i=1
while i <= n:
sum = sum + i
i=i+1
print("Sum:", sum)
avg = sum / n
print("Average:", avg)

#Output

b. Python program to find factorial, and Fibonacci of a


number, received by user, with iterative as well as
recursive process.

#Program Using iterative

print("Name : Sai nikhil\nUsn : 18BTRCE020")


n = int(input("enter number of terms to find fib and
fact : "))
p=int(input("enter 1st term in fibbanoccie:"))
q=int(input("enter 2nd term in fibbanoccie:"))

fact=1
i=1
while i<=n :
if i%2 == 0 :
p=p+q
print(i," st term Value : ",p)
fact = fact * i
i=i+1
else:
q=q+p
print(i," st term Value : ",q)
fact = fact * i
i=i+1

print("Factorial of ",n," = ",fact)

#Output
#Program Using Recursive
print("Name : nikhil\nUsn : 18BTRCE020")

def fact(n):
if n <= 1:
return n
else:
return n*fact(n-1)

n=int(input("enter number to find factorial :"))


if n < 0:
print("negative numbers not allowed")
elif n == 0:
print("factorial of 0 is 1")
else:
print("The factorial of", n, " is ", fact(n))
def Fib(n):
if n <= 1:
return n
else:
return (Fib(n - 1) + Fib(n - 2))

n = int(input("Enter the nth term to find fib : "))

if n <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
print(Fib(n))

#Output
#Program using recursive and iteration for to print a
range of values

print("Name : nikhil\nUsn : 18BTRCE020")


print("Factorial")
def fact(n):
if n <= 1:
return n
else:
return n*fact(n-1)

n=int(input("Enter the terms? "))


if n < 0:
print("negative numbers not allowed")
elif n == 0:
print("factorial of 0 is 1")
else:
for i in range(n):
print("i"," term of : ",fact(i))

print("Fibonacci")
def Fib(n):
if n <= 1:
return n
else:
return (Fib(n - 1) + Fib(n - 2))

n = int(input("Enter the terms? "))

if n <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(n):
print("i"," term of : ",Fib(i))

#Output
3a)To print all prime numbers between N and M.

print("Name : nikhil \nUsn : 18BTRCE020")


#n=int(input("enter number to find weather number
is prime or not? "))
m=int(input("Enter Starting Range of number:"))
n=int(input("Enter Ending Range Upto where we have
to find number:"))
flag: int=0
print("Prime Number List from ",m," to ",n)
for j in range(m,n):
flag=0
for i in range(1,j):
if(j%i == 0):
flag=flag+1

if(flag==1):
print(j)

//OUTPUT
3b)To find largest among three numbers, input by
user.
#large Number
print("Name: nikhil\nUsn: 18BTRCE020")
a=int(input("enter a value:"))
b=int(input("enter b value:"))
c=int(input("enter c value:"))
large = a
if(b>large):
large=b

if(c>large):
large=c
print(large," is a large")

//OUTPUT
3C)To find GCD for two numbers, input by user

#GCD
print("Name: nikhil\nUsn: 18BTRCE020")
a=int(input("enter divisor:"))
b=int(input("enter dividend:"))
while a!=b :
if(a>b):
a=a-b;
else:
b=b-a
print(a," is Your GCD");

//OUTPUT
4a)Elaborate string operations such as string
declaration, traversing, slicing, concatenating, and
sorting.

print("Name: nikhil\nUsn: 18BTRCE020")

#String declaration
print("String declaration??")
s="nikhil"
#String traversing
print("String traversing??")
s="nikhil"
for i in range(len(s)):
print(s[0:i])
#String slicing
print("String slicing??")
print(s[2:5])
#String concatenation
print("String concatenation??")
s1="sai"
s2="nikhil"
s=s1+" "+s2
print(s)
#String sorting
print("String sorting??")
s="suresh"
print(sorted(s))

//OUTPUT
4b)Implement a python script to check the element is
in the list or not by using linear search and Binary
search.

print("name:nikhil\nusn:18BTRCE020")
#Binary Search
def binary_search(lst, key):
low = 0
high = len(lst) - 1

while low <= high:


mid = (high + low) // 2
if (key == lst[mid]):
return mid

elif (key > lst[mid]):


low = mid + 1

else:
high = mid - 1
# if we reach here the element is not found
return -1

lst = []
n = int(input("Enter the size of list:"))
for i in range(n):
num = int(input("Enter the any number: \t"))
lst.append(num)
key = int(input("\nEnter the number to search:"))

index = binary_search(lst, key)


if index < 0:
print('{} was not found.'.format(key))

else:
print('{} was found at index {}'.format(key, index))
#Linear Search
lst=[]
n=int(input("Enter the size of list:"))
for i in range(n):
num = int(input("Enter the any number: \t"))
lst.append(num)
key = int(input("\nEnter the number to search:"))

found = False

for i in range(len(lst)):
if lst[i] == key:
found = True
print("\n{} found at index position
{}".format(key,i))
break
if found==False:
print("\n{} is not in list ".format(key))

//OUTPUT

4c) Implement a python script to arrange the


elements in sorted order using Bubble, Selection,
Insertion and Merge sorting techniques.

print("name:nikhil\nUsn:18BTRCE020")
# performing the bubble sort operation
def bubble_sort(lst):
n = len(lst)
for i in range(n - 1):
for j in range(0, n - i - 1):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]

lst = []
n = int(input("Enter the size of list:"))
for i in range(n):
num = int(input("Enter the any number: \t"))
lst.append(num)

print("list of element before sorting: \t")


for i in range(len(lst)):
print(lst[i], end='')

bubble_sort(lst)

print("\n list of element after sorting:\t")


for i in range(len(lst)):
print(lst[i], end='')
# Python program for implementation of Selection
# Sort
import sys

A = lst
# Traverse through all array elements
for i in range(len(A)):

# Find the minimum element in remaining


# unsorted array
min_idx = i
for j in range(i + 1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

# Swap the found minimum element with


# the first element
A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above


print("Sorted array")
for i in range(len(A)):
print("%d" % A[i]),

#python program to implement selection sort

//Output
# Python program for implementation of MergeSort
print("name:nikhil\nUsn:18BTRCE020")
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr) // 2 # Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves

mergeSort(L) # Sorting the first half


mergeSort(R) # Sorting the second half

i=j=k=0

# Copy data to temp arrays L[] and R[]


while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

# Checking if any element was left


while i < len(L):
arr[k] = L[i]
i += 1
k += 1

while j < len(R):


arr[k] = R[j]
j += 1
k += 1

def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
if __name__ == '__main__':
arr = [1,-10,100,11,-90]
print("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)

//OUTPUT

# perform insertion sort

def insertion_sort(lst):

for i in range(1, len(lst)):


temp = lst[i]

j=i-1

while (j >= 0 and temp < lst[j]):

lst[j + 1] = lst[j]

j=j-1

lst[j + 1] = temp

lst = []

n = int(input("Enter the size of list:"))

for i in range(n):

num = int(input("Enter the any number: \t"))

lst.append(num)

print("list of element before sorting: \t")

for i in range(len(lst)):

print(lst[i], end='')
insertion_sort(lst)

print("\n list of element after sorting:\t")

for i in range(len(lst)):

print(lst[i], end='')

//OUTPUT

5a)Implement python script to show the usage of


various operators available in python language.

#Program
print("name:nikhil\nUsn:18BTRCE020")
#To perform mathematical operations such as
addition, subtraction, multiplication, division, modulo,
and power
num1 = int(input('Enter First number: '))
num2 = int(input('Enter Second number '))
add = num1 + num2
dif = num1 - num2
mul = num1 * num2
div = num1 / num2
floor_div = num1 // num2
power = num1 ** num2
modulus = num1 % num2
print('Sum of ',num1 ,'and' ,num2 ,'is :',add)
print('Difference of ',num1 ,'and' ,num2 ,'is :',dif)
print('Product of' ,num1 ,'and' ,num2 ,'is :',mul)
print('Division of ',num1 ,'and' ,num2 ,'is :',div)
print('Floor Division of
',num1 ,'and' ,num2 ,'is :',floor_div)
print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)
print('Modulus of ',num1 ,'and' ,num2 ,'is :',modulus)

#the operator precedence


a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))
c = int(input('Enter 3rd number: '))
d = int(input('Enter 4th number: '))
e = int(input('Enter 5th number: '))

e = (a + b) * c / d
print ("Value of (a + b) * c / d is ", e)

e = ((a + b) * c) / d
print ("Value of ((a + b) * c) / d is ", e)

e = (a + b) * (c / d)
print ("Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d
print ("Value of a + (b * c) / d is ", e)

#logical operator
x = True
y = False

print('x and y is',x and y)

print('x or y is',x or y)
print('not x is',not x)
#Identity Operators
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x

print(x is z)

# returns True because z is the same object as x

print(x is y)

# returns False because x is not the same object as y,


even if they have the same content

print(x == y)
print(x is not y)
#MemberShip Operator
x = ["apple", "banana"]

print("banana" in x)
print('banana' not in x)

#Output
5b)Write a program to calculate overtime pay of 10
employees. Overtime is paid at the rate of Rs.12.00
per hour for every hour worked above 40 hours.
Assume that employee do not work for fractional part
of an hour.

#program

print("name:nikhil\nusn:18BTRCE020")
x=1
working_hours=0
over_time=0
over_time_pay=0

while(x <= 10):


working_hours=int(input("Enter working hours "))
if(working_hours > 40):
over_time = working_hours - 40
over_time_pay = over_time * 12.0
print("Employee No ",x)
print("overtime pay is",over_time_pay)
else:
print("You have to work for more than 40 hours to
get over time pay\n")
x=+1

#Output

a. Write a Pandas program to create and display a DataFrame


from a specified dictionary data which has the index labels.
b. To create a 4X2 integer array and prints its attributes

c. For the given numpy array return array of odd rows and
even columns..
d) To add the two NumPy arrays and modify a result array by
calculating the square root of each element.

1: Read Total profit of all months and show it using


a line plot

1) X label name = Month Number

2) Y label name = Total profit


2: Get Total profit of all months and show line plot
with the following Style properties
Generated line plot must include following Style
properties: –

• Line Style dotted and Line-color should be red


Show legend at the lower right location.
• X label name = Month Number Y label name
= Sold units number Add a circle marker.
• Line marker color as read
• Line width should be 3
Company_sales_data
8a) Draw the target symbol (a set of concentric
squares, alternating red and white) in a
graphics window, that is, 200 pixels wide by
200 pixels high. (Hint: Draw the target square
first in red, followed by next smaller square in
white, then draw the next smaller square in
red).
import matplotlib.pyplot as plt
plt.axes

rectangle=plt.Rectangle((0,0),200,200,fc='r')
plt.gca().add_patch(rectangle)
rectangle=plt.Rectangle((50,50),100,100,fc='w')
plt.gca().add_patch(rectangle)

rectangle=plt.Rectangle((75,75),50,50,fc='r')
plt.gca().add_patch(rectangle)

plt.axis('scaled')
plt.show()
OUTPUT:
8b) Create a 5x5 rectangle whose top left
corner is at (row*5, col*5). If the sum of the
rows and columns’ number is even, set the fill
color of the rectangle to white, otherwise set it
to the black. Then draw the rectangle.
#lab program 8b
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
plt.figure()
plt.axis([0,25,25,0])
currentAxis = plt.gca()
for i in range(0,5):
for j in range(0,5):
if((i+j)%2==0):

currentAxis.add_patch(Rectangle((i*5,j*5),5,5,c
olor='white'))
else:

currentAxis.add_patch(Rectangle((i*5,j*5),5,5,c
olor='black'))
plt.show()
OUTPUT:
home: create urls.py

from django.contrib import admin


from django.urls import path
from home import views

urlpatterns = [
path("",views.index,name='home'),

path("about",views.about,name='about'),

path("services",views.services,name="serv
ices"),

path("contact",views.contact,name="contac
t")

Views.py

from django.shortcuts import render,


HttpResponse
# Create your views here.
def index(request):
return HttpResponse("This is home
page")

def about(request):
return HttpResponse("This is about
page")

def services(request):
return HttpResponse("This is about
servivce page")

def contact(request):
return HttpResponse("This is about
contact page")

create 2 forlde out side folders.


Setting.py add manual content
STATICFILES_DIRS = [
BASE_DIR / "static",
'/var/www/static/',
]

Templates
Index.html

Static
Create text.txt file (don’t keep sensitive data
file)

Keep the data in template ------setting.py

http://127.0.0.1:8000/

Index.html
<!DOCTYPE html>
<html>
<body>

<h2>Width and Height Attributes</h2>

<p>The width and height attributes of the


img tag, defines the width and height of
the image:</p>

<b>{{variable}}</b>
</body>
</html>

Views.py
from django.shortcuts import render,
HttpResponse

# Create your views here.


# def index(request):
# return HttpResponse("This is home
page")
def index(request):
context={
"variable":"This is new Data sent
to Office"
}
return
render(request,'index.html',context)

def about(request):
return HttpResponse("This is about
page")

def services(request):
return HttpResponse("This is about
servivce page")

def contact(request):
return HttpResponse("This is about
contact page")

Experiment-10
Create a "Student" JSON document with the following fields:
Usn_No, Name, Branch, Contact_Numbers and Mail_Id.
Perform read and write operations on the above document
using python API's.
dictionary={
"name":"sai nikhil",
"usn":"18BRCE020",
"BRANCH":"CSE-MACT",
"PHONE NUMBER":"7036082622",
"EMAIL":"18btrce020@jainuniversity.ac.in"
}
json_object = json.dumps(dictionary,index=5)
with open("sample.json","w")as outfile:
outfile.write(json_object)
import jason
with open('sample.jason','r')as openfile:
json_object = json.load(openfile)
print(jason_object)
print(type(jason_object))

You might also like