0% found this document useful (0 votes)
7 views

Python_Lab_Manual_2023_24[1]

The document contains multiple Python programming tasks, including calculating average marks, checking for palindromes, converting number systems, and sorting algorithms. It also includes tasks for file operations, regular expressions, and interfacing with hardware components like LEDs and ultrasonic sensors. Each section provides code examples and expected outputs for various functionalities.
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)
7 views

Python_Lab_Manual_2023_24[1]

The document contains multiple Python programming tasks, including calculating average marks, checking for palindromes, converting number systems, and sorting algorithms. It also includes tasks for file operations, regular expressions, and interfacing with hardware components like LEDs and ultrasonic sensors. Each section provides code examples and expected outputs for various functionalities.
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/ 15

PART-A

1a. Write a python program to find the best of two test average marks out of
three test’s marks accepted from the user
#best of two test average marks out of three test’s marks accepted from the user
m1 = int (input("Enter the marks in the first test: "))
m2 = int (input("Enter the marks in second test: "))
m3 = int (input("Enter the marks in third test: "))
if (m1 > m2):
if (m2 > m3):
total = m1 + m2
else:
total = m1 + m3
elif (m1 > m3):
total = m1 + m2
else:
total = m2 + m3
Avg = total / 2
print ("The average of the best two test marks is: ",Avg)
OUTPUT
Enter the marks in the first test: 12
Enter the marks in second test: 22
Enter the marks in third test: 22
The average of the best two test marks is: 22.0

1b. Develop a Python program to check whether a given number is


palindrome or not and also count the number of occurrences of each digit in
the input number
#check if a number is a palindrome and count the number of digits
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")

n_str=str(temp)
for i in range(10):
if (n_str.count(str(i))>0):
print(i, "appears", n_str.count(str(i)),"times")
OUTPUT
Enter number:1289821
The number is a palindrome!
1 appears 2 times
2 appears 2 times
8 appears 2 times
9 appears 1 times

2a. Develop a python program to perform the following code conversions


using functions. a) Binary to Decimal b) Octal to Hexadecimal
def Bin2dec(bin):
l=len(bin)
dec=0
for i in range(l):
dec+=int(bin[i])*(2**(l-i-1))
return dec

def oct2hex(oct):
l=len(oct)
dec=0
for i in range(l):
dec+=int(oct[i])*(8**(l-i-1))
hexa=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
temp=' '
while dec>0:
rem=dec%16
temp+=hexa[rem]
dec//=16
octhex = temp[::-1]
return octhex

bin=input("Enter the Binary Number")


print('Binary to Decimal is',Bin2dec(bin))
oct=input("Enter the octal Number")
print('Octal to Hexadecimal is',oct2hex(oct))

OUTPUT

Enter the Binary Number1111


Binary to Decimal is 15
Enter the octal Number536
Octal to Hexadecimal is 15E

3. Write a Python program that accepts a sentence and find the following.
a) Number of words and digits
b) Number of uppercase letters and lowercase letters

Method I:
test_string = input("Enter a string : ")
digCnt = upCnt = loCnt =wordcnt=0
wordcont=len(test_string.split())
for ch in test_string:
if ch>='0' and ch<='9':
digCnt += 1
if ch>='A' and ch<='Z':
upCnt += 1
if ch>='a' and ch<='z':
loCnt += 1
print("The number of words in a string: ", wordcont)
print("The number of digits in a string: ",digCnt)
print("The number of upper case letters in a string: ",upCnt)

print("The number of lower case letters in a string: ",loCnt)

Method II:

test_string = input("Enter a string : ")


digCnt = upCnt = loCnt =wordcnt=0
wordcont=len(test_string.split())
for ch in test_string:
if ch.isdigit():
digCnt += 1
if ch.isupper():
upCnt += 1
if ch.islower():
loCnt += 1
print("The number of words in a string: ", wordcont)
print("The number of digits in a string: ",digCnt)
print("The number of upper case letters in a string: ",upCnt)
print("The number of lower case letters in a string: ",loCnt)
OUTPUT
Enter a string : PYTHON Programming Lab 22ECE136
The number of words in a string: 4
The number of digits in a string: 5
The number of upper case letters in a string: 11
The number of lower case letters in a string: 12

4. Write a python program to implement insertion sort and merge sort using
lists
a) Insertion sort
def insertion_sort(n, arr):
for i in range(1,n):
key = arr[i]
j = i-1
while j>=0 and key < arr[j]:
arr[j+1] = arr[j]
j -=1
arr[j+1] = key
return arr
n = int(input("Enter the size of array: "))
arr = [None]*n
print("Enter the elements: ")
for i in range(n):
arr[i] = int(input())
print("Before Sorting : ",arr)
insertion_sort(n, arr)
print("After Insertion sort : ",arr)
OUTPUT
Enter the size of array: 6
Enter the elements:
2
6
5
1
3
4
Before Sorting : [2, 6, 5, 1, 3, 4]
After Insertion sort : [1, 2, 3, 4, 5, 6]

b) Merge Sort
def merge_sort(arr):
n = len(arr)
if(n>1):
mid = n//2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)

i=j=k=0
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
while(i<len(L)):
arr[k] = L[i]
k+=1
i+=1
while(j<len(R)):
arr[k] = R[j]
k+=1
j+=1

n = int(input("Enter the size of array"))


arr = [None]*n
print("Enter the elements")
for i in range(n):
arr[i] = int(input())
print("Before Sorting : ",arr)
merge_sort(arr)
print("After Merge Sort : ",arr)

OUTPUT
Enter the size of array6
Enter the elements
2
6
5
1
3
4
Before Sorting : [2, 6, 5, 1, 3, 4]
After Merge Sort : [1, 2, 3, 4, 5, 6]
5. Write a program to convert roman numbers in to integer values using
Dictionaries.
def roman2integer(roman_numeral):
roman_dict={'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
res=0
pre_val=0
for symbol in roman_numeral[ : : -1]:
value=roman_dict[symbol]
if(value>=pre_val):
res=res+value
else:
res=res-value
pre_val=value
return res

roman_numeral=input("Enter a Roman numeral:")


integer_value=roman2integer(roman_numeral)
print("Integer value:", integer_value)
OUTPUT:
1.
Enter a Roman numeral: IVXLCDM
Integer value: 334
2.
Enter a Roman numeral: MDCLXVI
Integer value: 1666

6. Write a python program to accept a file name from the user and perform
the following operations.
a) Display the first N line of the file
b) Find the frequency of occurrence of the word accepted from the user in
the file
#i. to display N lines from file
#ii. to display frequency of occurrence of the word accepted from file
filename=input("Enter filename : ")
N=int(input("Enter number of lines to be displayed : "))
# Opening the given file in read-only mode
with open(filename, 'r') as filedata:
# Read the file lines using readlines()
linesList= filedata.readlines()
print("The following are the first",N,"lines of a text file:")
# Traverse in the list of lines to retrieve the first N lines of a file
for textline in (linesList[:N]):
# Printing the first N lines of the file line by line.
print(textline, end ='')
# Closing the input file
filedata.close()
word=input("Enter word to be searched:")
k=0
with open(filename, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)

OUTPUT
Enter filename : test_1.txt
Enter number of lines to be displayed : 5
The following are the first 5 lines of a text file:
Decision trees classify instances by sorting them down the tre
e from the root to some leaf node, which provides the classifi
cation of the instance.
Each node in the tree specifies a test of some attribute of th
e instance, and each branch descending from that node correspo
nds to one of the possible values for this attribute.
An instance is classified by starting at the root node of the
tree, testing the attribute specified by this node, then movin
g down the tree branch corresponding to the value of the attri
bute in the given example. This process is then repeated for t
he subtree rooted at the new node.
Enter word to be searched:is
Occurrences of the word:
2
7. Develop a python program to demonstrate Regular Expression.
a. Write a function to recognize a pattern 415-555-4242 using regular
expression.
import re
def checkphoneNo(num):
pattern=('\d{3}-\d{3}-\d{4}$')
result=re.match(pattern,num)
if result:
print("Valid Phone Number")
else:
print("Invalid Phone Number")
n=input("Enter Number\n")
print("Using Regular Expression")
res1=checkphoneNo(n)
b. Write a program using regular expression to search the email id in a given
string.
import re
lin = 'From [email protected] Sat Jan 5 09:14:16 2008'
y = re.findall('@([^ ]*)',lin)
print(y)
PART-B
1. Develop a Python program to turn ON and OFF LED for a specific time
and specific number of times.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(4,GPIO.OUT)
count = 1
while count<=10:
GPIO.output(4,GPIO.HIGH)
print("LED is ON")
time.sleep(1)
GPIO.output(4,GPIO.LOW)
print("LED is OFF")
time.sleep(1)
count+=1

2. Develop a Python program to count the number of person entered the


room using IR sensor.

import RPi.GPIO as GPIO


import time
irpin=4
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(irpin,GPIO.IN)
count=0
while True:
ir=GPIO.input(irpin)
if ir==0:
print("Person detected")
count+=1
print(count,"detected")
time.sleep(0.5)
else:
print("person not detected")
time.sleep(0.5)
if count==10:
break
else:
print("person not detected")
time.sleep(0.5)

3. Develop a Python program to measure the distance of an object using


Ultrasonic Sensor
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
TRIG = 16
ECHO = 20
print("Distance Measurement in progress")
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
while True:
GPIO.output(TRIG, False)
print("Waitng for the sensor to settle")
time.sleep(2)
GPIO.output(TRIG,True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
print("Distance: ",distance,"cm")
4. Develop a Python program to display the decimal numbers from 0 to 9
on Seven Segment Display.
import RPi.GPIO as GPIO
import time
#Seven Segment Equivalent Values are stored in a list
DISPLAY=[0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x67]
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(13,GPIO.OUT)#a
GPIO.setup(6,GPIO.OUT)#b
GPIO.setup(16,GPIO.OUT)#c
GPIO.setup(20,GPIO.OUT)#d
GPIO.setup(21,GPIO.OUT)#e
GPIO.setup(19,GPIO.OUT)#f
GPIO.setup(26,GPIO.OUT)#g
GPIO.setup(12,GPIO.OUT)#dp
# Put all the leds to off state
def port(pin):
if (pin & 0x01 == 0x01):
GPIO.output(13,1)
else:
GPIO.output(13,0)
if (pin & 0x02== 0x02):
GPIO.output(6,1)
else:
GPIO.output(6,0)
if (pin & 0x04 == 0x04):
GPIO.output(16,1)
else:
GPIO.output(16,0)
if (pin & 0x08== 0x08):
GPIO.output(20,1)
else:
GPIO.output(20,0)
if (pin & 0x10 == 0x10):
GPIO.output(21,1)
else:
GPIO.output(21,0)
if (pin & 0x20 == 0x20):
GPIO.output(19,1)
else:
GPIO.output(19,0)
if (pin & 0x40 == 0x40):
GPIO.output(26,1)
else:
GPIO.output(26,0)
if (pin & 0x80 == 0x80):
GPIO.output(12,1)
else:
GPIO.output(12,0)
while 1:
for x in range (10):
pin=DISPLAY[x]
port(pin)
time.sleep(1)

You might also like