0% found this document useful (0 votes)
116 views20 pages

PYTHON LAB MANUAL Name: Jitendra Kumar Roll No.: 05035304421 Section: 2

This document contains a Python lab manual with 20 questions and programs. It includes programs to generate natural numbers, find the sum of even Fibonacci terms, display numbers divisible by 7 but not 5, calculate cumulative product of a list, reverse a list without using the reverse function, calculate Fibonacci sequence recursively, print the first and last half of a tuple, count characters in a string and store in a dictionary, remove spaces from a string, compute lines, words and characters in a file, create a class to get and print a string in uppercase, create a circle class with area and perimeter methods, reverse a string word by word, print patterns using loops, calculate a series sum, compare two files, check balanced parentheses, use

Uploaded by

Daily Vlogger
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)
116 views20 pages

PYTHON LAB MANUAL Name: Jitendra Kumar Roll No.: 05035304421 Section: 2

This document contains a Python lab manual with 20 questions and programs. It includes programs to generate natural numbers, find the sum of even Fibonacci terms, display numbers divisible by 7 but not 5, calculate cumulative product of a list, reverse a list without using the reverse function, calculate Fibonacci sequence recursively, print the first and last half of a tuple, count characters in a string and store in a dictionary, remove spaces from a string, compute lines, words and characters in a file, create a class to get and print a string in uppercase, create a circle class with area and perimeter methods, reverse a string word by word, print patterns using loops, calculate a series sum, compare two files, check balanced parentheses, use

Uploaded by

Daily Vlogger
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/ 20

***** PYTHON LAB MANUAL *****

Name : Jitendra Kumar


Roll No.: 05035304421
Section : 2

Q 1. Implement Python Script to generate first N natural


numbers

Program :

number = int(input("Please Enter any Number: "))

print("The List of Natural Numbers from 1 to {0} are".format(number))

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

print (i, end = ' ')

OUTPUT :

Q 2. By considering the terms in the Fibonacci sequence whose


values do not exceed 1000, find the sum of the even-valued
terms
Program :

def evenFibSum(limit) :
if (limit < 2) :
return 0
ef1 = 0
ef2 = 2
sm= ef1 + ef2

while (ef2 <= limit) :

ef3 = 4 * ef2 + ef1


if (ef3 > limit) :
break
ef1 = ef2
ef2 = ef3
sm = sm + ef2

return sm
limit = 1000
print(evenFibSum(limit))

OUTPUT :

Q 3. Write a program which makes use of function to display


all such numbers which are divisible by 7 but are not a multiple
of 5, between 1000 and 2000.

Program :
def display(n1, n2):
results = []
for i in range(1000, 2000+1):
if (i%7==0) and (i%5!=0):
results.append(i)
return results
n1 = 1000
n2 = 2000
print(display(n1,n2))
OUTPUT :

Q 4. Write a function cumulative_product to compute


cumulative product of a list of numbers.

Program :
def product(list):
p =1
for i in list:
p *= i
print(p)
return p
arr= [1,2,3,4,5,6,7,8,9,10]
c=product(arr) ###### OUTPUT : >
Q 5.Write a function reverse to reverse a list. Without using the
reverse function.

Program :

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Before : ")
print(numbers)

L = len(numbers)

for i in range(int(L/2)):

n = numbers[i]
numbers[i] = numbers[L-i-1]
numbers[L-i-1] = n

print("After : ")
print(numbers)
OUTPUT :

Q 6.Write a function reverse to reverse a list. Without using the


reverse function.

Program :

def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = 10

if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

OUTPUT:

Q 7.With a given tuple (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), write a


program to print the
first half values in one line and the last half values in one line.

Program :

tp=(1,2,3,4,5,6,7,8,9,10)
tp1=tp[:5]
tp2=tp[5:]
print(tp1)
print(tp2)
OUTPUT :

Q 8. Write a program to count the numbers of characters in the


string and store them in a dictionary data structure.
Program :
str=input("enter string : ")
f = {}
for i in str:
if i in f:
f[i] += 1
else:
f[i] = 1
print(f)
OUTPUT :

Q 9. Write a program to count the numbers of characters in the


string and store them in a dictionary data structure.

Program :
def deletespace(name):
if(len(name)==0):
return ""
else:
str=""
if(ord[name[0]])>chr(65) and ord(name[0])<chr(122):
return str+deletespace(name[1:])
name=input("Please enter the name..")
deletespace(name)

Q 10. Write a program to compute the number of characters,


words and lines in a file
Program :
file__IO ="D:\\Jitendra\PythonrPrograms\python.txt"

with open(file__IO, 'r') as f:

data = f.read()

line = data.splitlines()

words = data.split()

spaces = data.split(" ")

charc = (len(data) - len(spaces))

print('\n Line number ::', len(line), '\n Words number ::',


len(words), '\n Spaces ::', len(spaces), '\n Characters ::',
(len(data)-len(spaces)))

OUTPUT :
Q 11.Write a Python class which has two methods get_String
and print_String. get_String accept a string from the user and
print_String print the stringin upper case

Program:
class IOString():
def __init__(self):
self.str1 = ""

def get_String(self):
self.str1 = input()

def print_String(self):
print(self.str1.upper())

print("Type any statement and this program will make it upper


case!")

str1 = IOString()
str1.get_String()
str1.print_String()

OUTPUT :
Q 12.Write a Python class named Circle constructed by a radius
and two methods which will compute the area and the perimeter
of a circle

Program:
class Circle():
def __init__(self, r):
self.radius = r

def area(self):
return self.radius**2*3.14

def perimeter(self):
return 2*self.radius*3.14

NewCircle = Circle(8)
print(NewCircle.area())
print(NewCircle.perimeter())

OUTPUT :
Q 13..Write a Python class to reverse a string word by word :
Input string : 'hello Python'
Expected Output : 'Python hello'

Program :
string = "my name is Jitendra kumar sharma"
s = string.split()[::-1]
l = []
for i in s:
l.append(i)
print("Original : "+string)
print("Reversed : ")
print(" ".join(l))

OUTPUT :

Q 14. Write python functions to produce following output


patterns:
Program :

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


k=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print(i, end=" ")
k += 1
k=0
print()

Q 15. Write a function that finds the sum of first n terms of


following series: 1 – x2 / 2! + x4 / 4! – x6 / 6! + …… xn / n!

Q 16. Write a program to compare two files and display total


number of lines in a file.

Q 18. Write a program to determine whether a given string has


balanced parenthesis or not.

Program :

def isbalanced(s):
c= 0
ans=False
for i in s:
if i == "(":
c += 1
elif i == ")":
c-= 1
if c < 0:
return ans
if c==0:
return not ans
return ans
s="{[]}"
print("Given string is balanced :",isbalanced(s))

OUTPUT :
Q 19.Implement a python script to check the element is in the
list or not by using Linear search & Binary search.

Program :

def LinearSearch(array, n, k):


for j in range(0, n):
if (array[j] == k):
return j
return -1
array = [1, 3, 5, 7, 9]
k = int(input("Number to be search : "))
n = len(array)
result = LinearSearch(array, n, k)
if(result == -1):
print("Element not found")
Else:
print("Element found at index: ", result)

OUTPUT :

Q 20.Implement a python script to arrange the elements in


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

Program :

#Bubble sort
def bubblesrt(list):
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
list = [19,2,31,45,6,11,121,27]
bubblesrt(list)
print("Bubble Sort : ")
print(list)
print()
#merger sort

def merge(arr, l, m, r):


n1 = m - l + 1
n2 = r - m
L = [0] * (n1)
R = [0] * (n2)
for i in range(0, n1):
L[i] = arr[l + i]

for j in range(0, n2):


R[j] = arr[m + 1 + j]
i=0
j=0
k=l

while i < n1 and j < n2:


if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

while i < n1:


arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1

def mergeSort(arr, l, r):


if l < r:
m = l+(r-l)//2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)

arr = [19,2,31,45,6,11,121,27]
n = len(arr)
# print("Given array is")
# for i in range(n):
# print("%d" % arr[i],end=" ")

mergeSort(arr, 0, n-1)
print("\n\nSorted array is (Merge Sort) ")
for i in range(n):
print("%d" % arr[i],end=" ")

# Insertion sort in Python

def insertionSort(array):
for step in range(1, len(array)):
key = array[step]
j = step - 1

while j >= 0 and key < array[j]:


array[j + 1] = array[j]
j=j-1

array[j + 1] = key

data = [19,2,31,45,6,11,121,27]
insertionSort(data)
print()
print()
print('Insertion sort : ')
print(data)

# Selection sort in Python

def selectionSort(array, size):

for step in range(size):


min_idx = step

for i in range(step + 1, size):


if array[i] < array[min_idx]:
min_idx = i

(array[step], array[min_idx]) = (array[min_idx],


array[step])

data =[19,2,31,45,6,11,121,27]
size = len(data)
selectionSort(data, size)
print()
print()
print('Selection sort :')
print(data)

OUTPUT :
Q 23.Write a python code for simple GUI calculator using Tk.

Program :
from tkinter import *
def iCalc(source, side):
storeObj = Frame(source, borderwidth=4, bd=4, bg="powder
blue")
storeObj.pack(side=side, expand =YES, fill =BOTH)
return storeObj
def button(source, side, text, command=None):
storeObj = Button(source, text=text, command=command)
storeObj.pack(side=side, expand = YES, fill=BOTH)
return storeObj
class app(Frame):
def __init__(self):
Frame.__init__(self)
self.option_add('*Font', 'arial 20 bold')
self.pack(expand = YES, fill =BOTH)
self.master.title('Calculator')
if __name__=='__main__':
app().mainloop()

OUTPUT :

You might also like