[go: up one dir, main page]

0% found this document useful (0 votes)
13 views21 pages

Record_python_final1

The document contains various Python programming exercises and their corresponding codes, including programs for calculating Disarium numbers, counting letter occurrences in a file, implementing a Caesar cipher, playing rock-paper-scissors, color detection in images, and a simple dictionary application. Each program is aimed at demonstrating different programming concepts and functionalities. Additionally, there are examples of games like dice rolling and hangman.

Uploaded by

Ragavi A
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views21 pages

Record_python_final1

The document contains various Python programming exercises and their corresponding codes, including programs for calculating Disarium numbers, counting letter occurrences in a file, implementing a Caesar cipher, playing rock-paper-scissors, color detection in images, and a simple dictionary application. Each program is aimed at demonstrating different programming concepts and functionalities. Additionally, there are examples of games like dice rolling and hangman.

Uploaded by

Ragavi A
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Program Code:

def calculateLength(n):
length = 0
while(n != 0):
length = length + 1
n = n//10
return length
num = int(input("Enter a number:"))
rem = sum = 0
len = calculateLength(num)
#Makes a copy of the original number num
n = num
#Calculates the sum of digits powered with their respective position
while(num> 0):
rem = num%10
sum = sum + int(rem**len)
num = num//10
len = len - 1
#Checks whether the sum is equal to the number itself
if(sum == n):
print(str(n) + " is a Disarium number")
else:
print(str(n) + " is not a Disarium number")

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Output :

Result:

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Program Code:

fname=input ("Enter file name: ")


l=input ("Enter letter to be searched:")
k =0
with open (“c://test/+fname,'r') as f:
for line in f:
words =line.split()
for i in words:
for letter in i:
if (letter==l):
k=k+1
print ("Occurrences of the letter:")
print (k)

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Output :

Result:

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Program Code:
plaintext = input("Please enter your plaintext: ")
shift = input("Please enter your key: ")
alphabet = "abcdefghijklmnopqrstuvwxyz"
ciphertext = ""
# shift value can only be an integer
while isinstance(int(shift), int) == False:
# asking the user to reenter the shift value
shift = input("Please enter your key (integers only!): ")
shift = int(shift)
new_ind = 0
# this value will be changed later
for i in plaintext:
if i.lower() in alphabet:
new_ind = alphabet.index(i) + shift
ciphertext += alphabet[new_ind % 26]
else:
ciphertext += i
print("The ciphertext is: " + ciphertext)

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Output :

Result:

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Program Code:

import random
user_action = input("Enter a choice (rock, paper, scissors): ")
possible_actions = ["rock", "paper", "scissors"]
computer_action = random.choice(possible_actions)
print(f"\nYou chose {user_action}, computer chose {computer_action}.\n")
if user_action == computer_action:
print("Both players selected {user_action}. It's a tie!")
elif user_action == "rock":
if computer_action == "scissors":
print("Rock smashes scissors! You win!")
else:
print("Paper covers rock! You lose.")
elif user_action == "paper":
if computer_action == "rock":
print("Paper covers rock! You win!")
else:
print("Scissors cuts paper! You lose.")
elif user_action == "scissors":
if computer_action == "paper":
print("Scissors cuts paper! You win!")
else:
print("Rock smashes scissors! You lose.")

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Output :

Result:

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Program Code:
import re
def text_match(text):
patterns ='[A-Z]+[a-z]+$'
if re.search(patterns, text):
return 'Found a match!'
else:
return ('Not matched!')
print(text_match("AaBbGg"))
print(text_match("Python"))
print(text_match("python"))
print(text_match("PYTHON"))
print(text_match("aA"))
print(text_match("Aa"))

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Output :

Result:

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Program Code:
import cv2
import numpy as np
import pandas as pd
import argparse

#Creating argument parser to take image path from command line


ap = argparse.ArgumentParser();
ap.add_argument('-i', '--image', required=True, help="Image Path");
args = vars(ap.parse_args());
img_path = args['image'];

#Reading the image with opencv


img = cv2.imread(img_path);

#declaring global variables (are used later on)


clicked = False;
r = g = b = xpos = ypos = 0;

#Reading csv file with pandas and giving names to each column
index=["color","color_name","hex","R","G","B"];
csv = pd.read_csv('colors.csv', names=index, header=None);

#function to calculate minimum distance from all colors and get the most
matching color

def getColorName(R,G,B):
minimum = 10000;
for i in range(len(csv)):
d = abs(R- int(csv.loc[i,"R"])) + abs(G- int(csv.loc[i,"G"]))+ abs(B-
int(csv.loc[i,"B"]));
if(d<=minimum):
minimum = d;
cname = csv.loc[i,"color_name"]
return cname;

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


#function to get x,y coordinates of mouse double click

def draw_function(event, x,y,flags,param):


if event == cv2.EVENT_LBUTTONDBLCLK:
global b,g,r,xpos,ypos, clicked
clicked = True
xpos = x
ypos = y
b,g,r = img[y,x]
b = int(b)
g = int(g)
r = int(r)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_function);
while(1):
cv2.imshow("image",img)

if (clicked):
#cv2.rectangle(image, startpoint, endpoint, color, thickness)-1 fills entire rectangle
cv2.rectangle(img,(20,20), (750,60), (b,g,r), -1);

#Creating text string to display( Color name and RGB values )


text = ' R='+ str(r) + ' G='+ str(g) + ' B='+ str(b);

#cv2.putText(img,text,start,font(0-7),fontScale,color,thickness,lineType )
cv2.putText(img, text,(50,50),2,0.8,(255,255,255),2,cv2.LINE_AA);

#For very light colours we will display text in black colour


if(r+g+b>=600):
cv2.putText(img, text,(50,50),2,0.8,(0,0,0),2,cv2.LINE_AA)
clicked=False

#Break the loop when user hits 'esc' key


if cv2.waitKey(20) & 0xFF ==27:
break

cv2.destroyAllWindows()

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Output :

Result:

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Program Code:

import json
from difflib import get_close_matches
# Loading data from json file
# in python dictionary
data =json.load(open("c://test/+” “dictionary.json"))
def translate(w):
# converts to lower case
w =w.lower()
if w in data:
return data[w]
# for getting close matches of word
elif len(get_close_matches(w, data.keys())) > 0:
yn =input("Did you mean % s instead? Enter Y if yes, or N if no:
"%get_close_matches(w, data.keys())[0])
yn =yn.lower()
if yn =="y":
return data[get_close_matches(w, data.keys())[0]]
elif yn =="n":
return "The word doesn't exist. Please double check it."
else:
return "We didn't understand your entry."
else:
return "The word doesn't exist. Please double check it."
# Driver code
word =input("Enter word: ")
output =translate(word)
if type(output) ==list:
for item in output:
print(item)
else:
print(output)
input('Press ENTER to exit')

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Output :

Result:

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Program Code:

import random
min = 1
max = 6

roll_again = "yes"

while roll_again == "yes" or roll_again == "y":


print("Rolling the dices...")
print("The value is....")
print(random.randint(min, max))
roll_again =input("Roll the dices again?")

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Output :

Result:

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Program Code:

import random
hidden =random.randrange(1,201)
guess =int(input("Please enter your guess: "))
if guess == hidden:
print("Hit!")
elif guess < hidden:
print("Your guess is too low")
else:
print("Your guess is too high")
print(hidden)

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Output :

Result:

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Program Code:

import time
name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman!")
print (" ")
time.sleep(1)
print ("Start guessing...")
time.sleep(0.5)
word = "secret"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char)
else:
print ("_",)
failed += 1
if failed == 0:
print ("You won" )
break
guess = input("guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print ("Wrong")
print ("You have", + turns, 'more guesses' )

if turns == 0:
print ("You Lost" )

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:


Output :

Result:

Class: II M.Sc. IT Subject : PYTHON PROGRAMMING LAB Pg.No.:

You might also like