0% found this document useful (0 votes)
20 views46 pages

Lab Manual of Python

Uploaded by

as5169906
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)
20 views46 pages

Lab Manual of Python

Uploaded by

as5169906
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/ 46

E - Lab Manual

on

Digital Logic Design


B. Tech. (Computer Science & Engineering)

ThirdYear
CS-366

Compiled and Edited


by
Ms. Aakanksha
Joshi

Department of Computer Science & Engineering

College of Technology and Engineering Maharana


Pratap University of Agriculture and Technology
Udaipur – 313001
INDEX
S. No. TITLE OF EXPERIMENTS
1. Write a program to print “Hello”.
Write a program to find the Area and Circumference of
2.
a Circle.
3. Write a program to find the Addition of two numbers.
4. Write a program to find Simple Interest.
5. Write a program to find the Square Root.
6. Write a program to Swap two numbers.
7. Write a program to check number is Even or Odd.
Write a program to find the largest among three
8.
numbers.
9. Write a program to print the Table of a number.
10. Write a program to find the Sum of Natural Numbers.
Write a program to print Prime Numbers between 900 to 1000.
11.
12. Write a program to print Reverse String.
13. Write a program to print right-angled ‘#’ Pattern.
Write a program to display the Fibonacci sequence upto
14.
n-th terms.
Write a program to convert decimal into other number systems.
15.
Write a program to display the Calendar of the given
16.
month and year.
17. Write a program to add two matrices using nested loop.
Write a program to check Armstrong numbers in a
18.
certain interval.
Write a program to find that the number is positive or negative using ladder if-else.
19.
Write a program to find that the number is positive or
20.
negative using nested if-else.
21. Write a program to find the Factors of a number.
22. Write a program to make a Simple Calculator.
23. Write a program to find the L.C.M of two input numbers.
Write a program to display the powers of 2 using anonymous function.
24.
Write a program to display the Fibonacci sequence using Recursion.
25.
Write a program to transpose a matrix using a nested
26.
loop.
Write a program to sort alphabetically the words from a
27.
string provided by the user.
Write a program to find the Sum of Natural Numbers using Recursion.
28.
Write a program to find the Factorial of a Number using
29.
Recursion.
Write a program to print Binary Number using
30.
Recursion.
31. Write a program to remove Punctuations from a String.
32. Write a program to check if the two strings are Anagram.
Write a program to use a Global Variable in Nested
33.
Function.
34. Write a program to import a module.
35. Write a program to count the number of each vowel.
36. Write a program to mail merge.
Write a program to find the Size (Resolution) of an
37.
Image.
Write a program to catch Multiple Exceptions as a Parenthesized Tuple (in one line).
38.

39. Write a program to Split a List into Evenly Sized Chunks.


40. Write a program to find the Hash of a File & display it.
Write a program to return Multiple Values from a
41.
Function.
42. Write a program for Catching Exceptions in Python.
PROGRAM 1
OBJECT – Write a program to print “Hello”.

CODE –
#print('Hello')
str = 'Hello'
print(str)

OUTPUT –
PROGRAM 2

OBJECT – Write a program to find the Area and Circumference of a Circle.

CODE –
Radius = float(input('Enter The Radius of Circle - '))
Circumference = 2*3.14*Radius
Area = 3.14*Radius*Radius
print('Circumference of the Circle = ', Circumference)
print('Area of the Circle = ', Area)

OUTPUT –
PROGRAM -3

OBJECT – Write a program to find the Addition of two numbers.

CODE –
Num1 = int(input('Enter The First Number - '))
Num2 = int(input('Enter The Second Number - '))
#sum = Num1 + Num2
print('Sum of the two numbers = ', Num1+Num2)

OUTPUT –
PROGRAM -4

OBJECT – Write a program to find Simple Interest.

CODE –
P = float(input('Enter the Principal Amount - '))
R = float(input('Enter the Rate - '))
T = float(input('Enter the Time - '))
print('Simple Interest = ', P*R*T/100)

OUTPUT –
PROGRAM -5

OBJECT – Write a program to find the Square Root.

CODE –
Num = int(input('Enter the Number - '))
print('The Square Root - ', Num**0.5)

#import math
#print(math.sqrt(4))

OUTPUT –
PROGRAM -6

OBJECT – Write a program to Swap two numbers.

CODE –
a = int(input("Enter the First Number - "))
b = int(input("Enter the Second Number - "))
print("NUMBERS ARE ", a, b)
c=a
a=b
b=c
print("SWAPPED NUMBERS ARE ", a, b)

OUTPUT –
PROGRAM -7

OBJECT – Write a program to check number is Even or Odd.

CODE –
Num = int(input("Enter the Number - "))
if(Num%2==0):
print(Num, "is an Even Number")
else:
print(Num, " is an Odd Number")

OUTPUT –
PROGRAM -8

OBJECT – Write a program to find the largest among three numbers.

CODE –
a = int(input("Enter the First Number - "))
b = int(input("Enter the Second Number - "))
c = int(input("Enter the Third Number - "))
if(a>b and a>c):
print("The greatest number is ", a)
elif(b>a and b>c):
print("The greatest number is ", b)
elif(c>a and c>b):
print("The greatest number is ", c)
else:
print("All the three numbers are equal")

OUTPUT –
PROGRAM -9

OBJECT – Write a program to print the Table of a number.

CODE –
Num = int(input("Enter the Number - "))
print("Table of ", Num)
for i in range(0,11):
print(Num, 'x', i, '=', Num*i)

OUTPUT –
PROGRAM -10

OBJECT – Write a program to find the Sum of Natural Numbers.

CODE –
num = int(input("Enter the Number - "))
n = num*(num+1)/2
print("Sum = ", n)

if num < 0:
print("Enter a positive number")
else:
sum = 0
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)

OUTPUT –
PROGRAM -11

OBJECT – Write a program to print Prime Numbers between 900 to 1000.

CODE –
lower = 900
upper = 1000
print("PRIME NUMBERS BETWEEN", lower, "&", upper)
for i in range(lower, upper+1):
for n in range(2, i):
if(i%n==0):
break
else:
print(i)

OUTPUT –
PROGRAM -12

OBJECT – Write a program to print Reverse String.

CODE –
#string = input("Enter the String - ")
#for word in reversed(string):
# print(word)

s=input("Enter the String - ")


def reverse(s):
str = ""
for i in s:
str = i + str
return str
print("Original String - ", s)
print("Reversed String - ", reverse(s))

OUTPUT –
PROGRAM -13

OBJECT – Write a program to print right-angled ‘#’ Pattern.

CODE –
for i in range(0,5):
for j in range(0,i+1):
print("#", end="")
print()

OUTPUT –
PROGRAM -14

OBJECT – Write a program to display the Fibonacci sequence upto n-th terms.

CODE –
n_terms = int(input("Enter the Number of Terms Required - "))
n1, n2 = 0, 1
c=0
if n_terms <=0:
print("INVALID!..!Please enter a positive integer!")
elif n_terms == 1:
print("FIBONACCI SERIES UPTO", n_terms, "TERM")
print(n1)
else:
print("FIBONACCI SERIES UPTO", n_terms, "TERMS")
while c < n_terms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
c += 1

OUTPUT –
PROGRAM -15

OBJECT – Write a program to convert decimal into other number systems.

CODE –
dec = int(input("Enter the Decimal Value - "))
print("Binary Value = ", bin(dec))
print("Octal Value = ", oct(dec))
print("Hexadecimal Value = ", hex(dec))

OUTPUT –
PROGRAM -16

OBJECT – Write a program to display the Calendar of the given month and year.

CODE –
import calendar
yy = int(input("Enter year - "))
mm = int(input("Enter month - "))
print(calendar.month(yy, mm))

OUTPUT –
PROGRAM -17

OBJECT – Write a program to add two matrices using nested loop.

CODE –
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)

OUTPUT –
PROGRAM -18

OBJECT – Write a program to check Armstrong numbers in a certain interval.

CODE –
a = 100
b = 2000
print("ARMSTRONG NUMBERS between", a, "and", b, "are")
for num in range (a, b):
order = len(str(num))
sum = 0
temp = num
while (temp > 0):
digit = temp % 10
sum += digit**order
temp//=10
if (num == sum):
print(num)

OUTPUT –
PROGRAM -19

OBJECT – Write a program to find that the number is positive or negative using ladder if-else.

CODE –
num = float(input("Enter the Number - "))
if num > 0:
print(num, "IS A POSITIVE NUMBER")
elif num == 0:
print(num, "IS A ZERO INTEGER")
else:
print(num, "IS A NEGATIVE NUMBER")

OUTPUT –
PROGRAM -20

OBJECT – Write a program to find that the number is positive or negative using nested if-else.

CODE –
num = float(input("Enter the Number - "))
if num >= 0:
if num == 0:
print(num, "IS A ZERO INTEGER")
else:
print(num, "IS A POSITIVE NUMBER")
else:
print(num, "IS A NEGATIVE NUMBER")

OUTPUT –
PROGRAM -21

OBJECT – Write a program to find the Factors of a number.

CODE –
def print_factors(x):
print("The Factors of", x)
for i in range(1, x+1):
if x%i == 0:
print(i)
num = int(input("Enter the Number - "))
print_factors(num)

OUTPUT –
PROGRAM – 22

OBJECT – Write a program to make a Simple Calculator.

CODE –
# This function adds the two numbers
def add(x, y):
return x + y

# This function subtracts the two numbers


def subtract(x, y):
return x - y

# This function multiplies the two numbers


def multiply(x, y):
return x * y

# This function divides the two numbers


def divide(x, y):
return x / y

print("Select the Operation - ")


print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

while True:
# take input from the user
choice = input("Enter the choice(1/2/3/4): ")

# check if choice is one of the four options


if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation


# break the while loop if answer is no
next_calculation = input("Let's do the next calculation? (yes/no): ")
if next_calculation == "no":
break

else:
print("Invalid Input")

OUTPUT –
PROGRAM – 23

OBJECT – Write a program to find the L.C.M. of two input numbers.

CODE –
def compute_lcm(x, y):

# choose the greater number


if x > y:
greater = x
else:
greater = y

while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1

return lcm

num1 = int(input("Enter the First Number - "))


num2 = int(input("Enter the Second Number - "))

print("The L.C.M. of", num1, "and", num2, "is", compute_lcm(num1, num2))

OUTPUT –
PROGRAM – 24

OBJECT – Write a program to display the powers of 2 using anonymous function.

CODE –
terms = int(input("How many number of terms? - "))

# use anonymous function


result = list(map(lambda x: 2 ** x, range(terms)))

print("The total number of terms are - ", terms)


for i in range(terms):
print("2 raised to power",i,"is",result[i])

OUTPUT –
PROGRAM – 25

OBJECT – Write a program to display the Fibonacci sequence using Recursion.

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

nterms = int(input("Enter the number of terms - "))

# check if the number of terms is valid


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

OUTPUT –
PROGRAM – 26

OBJECT – Write a program to transpose a matrix using a nested loop.

CODE –
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
print("The Matrix X is ", X)
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[j][i] = X[i][j]
print("The Transpose of Matrix X is ")
for r in result:
print(r)

OUTPUT –
PROGRAM – 27

OBJECT – Write a program to sort alphabetically the words from a string provided by the user.

CODE –
#my_str = "Hello this Is an Example With cased letters"
# To take input from the user
my_str = input("Enter a String - ")

# breakdown the string into a list of words


words = [word.lower() for word in my_str.split()]

# sort the list


words.sort()

# display the sorted words


print("The sorted words are:")
for word in words:
print(word)

OUTPUT –
PROGRAM – 28

OBJECT – Write a program to find the Sum of Natural Numbers using Recursion.

CODE –
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)

# change this value for a different result


num = int(input("Enter the Number - "))

if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))

OUTPUT –
PROGRAM – 29

OBJECT – Write a program to find the Factorial of a Number using Recursion.

CODE –
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num = int(input("Enter the Number - "))


# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

OUTPUT –
PROGRAM – 30

OBJECT – Write a program to print Binary Number using Recursion.

CODE –
def convertToBinary(n):
if n > 1:
convertToBinary(n//2)
print(n % 2,end = '')

dec = int(input("Enter the Decimal Value - "))


print("Binary Value = ") convertToBinary(dec)

OUTPUT –
PROGRAM – 31

OBJECT – Write a program to remove Punctuations from a String.

CODE –
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

# my_string = "Hello!!!, he said ---and went."

# To take input from the user


my_string = input("Enter the string: ")

# remove punctuation from the string


no_punctuation = ""
for char in my_string:
if char not in punctuations:
no_punctuation = no_punctuation + char

# display the unpunctuated string


print(no_punctuation)

OUTPUT –
PROGRAM – 32

OBJECT – Write a program to check if the two strings are Anagram.

CODE –
# str1 = "Race"
# str2 = "Care"
# input from the user
str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")

# convert both the strings into lowercase


str1 = str1.lower()
str2 = str2.lower()

# check if length is same


if(len(str1) == len(str2)):

# sort the strings


sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)

# if sorted char arrays are same


if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")

OUTPUT –
PROGRAM – 33

OBJECT – Write a program to use a Global Variable in Nested Function.

CODE –
def foo():
x = 20

def bar():
global x
x = 25

print("Value of x before calling bar - ", x)


print("Now, on calling bar")
bar()
print("Value of x after calling bar - ", x)

foo()
print("Value of x in main - ", x)

OUTPUT –
OBJECT – Write a program to import a module.

CODE –
# import statement example to import standard module math

import math
print("(Importing Module) The value of pi = ", math.pi)

# import module by renaming it

import math as m
print("(Importing & Renaming Module) The value of pi = ", m.pi)

OUTPUT –
PROGRAM – 35

OBJECT – Write a program to count the number of each vowel.

CODE –
# string of vowels
vowels = 'aeiou'

ip_str = input("Enter the String - ")


# ip_str = 'Hello, My name is Ojasvi Chaplot'

# make it suitable for caseless comparisions


ip_str = ip_str.casefold()

# make a dictionary with each vowel a key and value 0


count = {}.fromkeys(vowels,0)

# count the vowels


for char in ip_str:
if char in count:
count[char] += 1

print(count)

OUTPUT –
PROGRAM – 36

OBJECT – Write a program to mail merge.

CODE –
# Names are in the file names.txt
# Body of the mail is in body.txt

# open names.txt for reading


with open("names.txt", 'r', encoding='utf-8') as names_file:

# open body.txt for reading


with open("body.txt", 'r', encoding='utf-8') as body_file:

# read entire content of the body


body = body_file.read()

# iterate over names


for name in names_file:
mail = "Hello " + name.strip() + "\n" + body

# write the mails to individual files


with open(name.strip()+".txt", 'w', encoding='utf-8') as mail_file:
mail_file.write(mail)

OUTPUT –
PROGRAM – 37

OBJECT – Write a program to find the Size (Resolution) of an Image.

CODE –
def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file passed into it"""

# open image for reading in binary mode


with open(filename,'rb') as img_file:

# height of image (in 2 bytes) is at 164th position


img_file.seek(1050)

# read the 2 bytes


a = img_file.read(2)

# calculate height
height = (a[0] << 8) + a[1]

# next 2 bytes is width


a = img_file.read(2)

# calculate width
width = (a[0] << 8) + a[1]

print("The resolution of the image is",width,"x",height)

jpeg_res("Clouds.jpg")

OUTPUT –
PROGRAM – 38

OBJECT – Write a program to catch Multiple Exceptions as a Parenthesized Tuple (in one line).

CODE –

string = input()
try:
num = int(input())
print(string+num)
except (TypeError, ValueError) as e:
print(e)

OUTPUT –
PROGRAM – 39

OBJECT – Write a program to Split a List into Evenly Sized Chunks.

CODE –
def split(list_a, chunk_size):

for i in range(0, len(list_a), chunk_size):


yield list_a[i:i + chunk_size]

# chunk_size = 2
chunk_size = int(input("Enter the Chunk Size - "))
# my_list = [1,2,3,4,5,6,7,8,9]
my_list = []
n = int(input("Enter the number of elements in the List - "))
for i in range(0, n):
element = int(input("Enter the elements - "))
my_list.append(element)
print(list(split(my_list, chunk_size)))

OUTPUT –
PROGRAM – 40

OBJECT – Write a program to find the Hash of a File & display it.

CODE –
# Python program to find the SHA-1 message digest of a file

# importing the hashlib module


import hashlib

def hash_file(filename):
""""This function returns the SHA-1 hash
of the file passed into it"""

# make a hash object


h = hashlib.sha1()

# open file for reading in binary mode


with open(filename,'rb') as file:

# loop till the end of the file


chunk = 0
while chunk != b'':
# read only 1024 bytes at a time
chunk = file.read(1024)
h.update(chunk)

# return the hex representation of digest


return h.hexdigest()

message = hash_file("joy-of-travel-6671.mp3")
print(message)

OUTPUT –
PROGRAM – 41

OBJECT – Write a program to return Multiple Values from a Function.

CODE –
# Return values using comma
print("Return Values Using Comma")
def name():
return "Ojasvi","Jarvis"

# print the tuple with the returned values


print(name())

# get the individual items


name_1, name_2 = name()
print(name_1, name_2)

# Using a Dictionary
print("Return Values Using a Dictionary")
def name():
n1 = "Ojasvi"
n2 = "Jarvis"

return {1:n1, 2:n2}

names = name()
print(names)

OUTPUT –
PROGRAM – 42

OBJECT – Write a program for Catching Exceptions in Python.

CODE –
# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:


try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!", sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)

OUTPUT –

You might also like