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

CBCS Mangalore University Python Programs

The document contains 4 Python programs: 1) Find sequences of uppercase followed by lowercase letters in a text, 2) Match words containing 'z' in a text, 3) Match strings containing letters, numbers and underscores, 4) Remove leading zeros from IP addresses.
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)
82 views

CBCS Mangalore University Python Programs

The document contains 4 Python programs: 1) Find sequences of uppercase followed by lowercase letters in a text, 2) Match words containing 'z' in a text, 3) Match strings containing letters, numbers and underscores, 4) Remove leading zeros from IP addresses.
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/ 24

NOTE!

 Blue colored lines in the code are keywords


 Green colored lines in the code are string constants
 Black colored contents in the code are literals and operators
PART A
Program 1: Program to input N numbers into array and separate prime numbers
and display them.
from array import *

prime = []
x = array('i', [])
n = int(input("Enter the no of elements: "))
print("Enter the", n, "elements")
for i in range(n):
x.append(int(input()))
print(x)

for num in x:
if num==1:
continue
for i in range(2, n-1):
if num % i == 0:
break
else:
if num not in prime:
prime.append(num)
print("Prime numbers in the given array is: ", prime, end=" ")
Program 2: Program, using user-defined functions to find the area of rectangle,
square, circle and triangle by accepting suitable input parameters from user.
def rectangle():
l = float(input("Enter the length of the rectangle: "))
b = float(input("Enter the breadth of the rectangle: "))
print("Area of the rectangle is: ", l * b, "Sq.Units")

def square():
s = float(input("Enter the side of the square: "))
print("Area of the square is: ", s * s, "Sq.Units")

def circle():
r = float(input("Enter the radius of the Circle: "))
print("Area of the circle is: ", 3.14 * r * r, "Sq.Units")

def triangle():
a = float(input("Enter the length of first side of the triangle:
"))
b = float(input("Enter the length of the second side of the
triangle: "))
c = float(input("Enter the length of the third side of the
triangle: "))
s = (a + b + c) / 2
area = ((s - a) * (s - b) * (s - c)) ** 0.5
print("Area of the triangle is: ", area, "Sq.Units")

while True:
print("Menu: \n"
"1. Rectangle "
"2. Square "
"3. Circle "
"4. Triangle "
"5. Exit ")
x = int(input("Enter your choice from 1 to 5: "))
if x == 1:
rectangle()
elif x == 2:
square()
elif x == 3:
circle()
elif x == 4:
triangle()
elif x == 5:
break;
else:
print("Invalid entry! Try again.")
Program 3: Consider a tuple t1= (1,2,5,7,9,2,4,6,8,10). Write a program to
perform following operations:
a. Print half the values of tuple in one line and the other half in the next line.
b. Print another tuple whose values are even numbers in the given tuple.
c. Concatenate a tuple t2= (11,13,15) with t1.
d. Return maximum and minimum value from this tuple
t1 = (1, 2, 5, 7, 9, 2, 4, 6, 8, 10)
print("Given tuple is: ", t1)
tp1 = t1[:5]
tp2 = t1[5:]
print("After dividing the tuple into two equal halves: ")
print("1st half: ", tp1)
print("Second half: ", tp2)
newt = list()
for i in range(len(t1)):
if t1[i] % 2 == 0:
newt.append(t1[i])
print("Even numbers in the given tuple are: ", tuple(newt))
t2 = (11, 13, 15)
print("Tuple 1: ", t1)
print("Tuple 2:", t2)
print("Concatenated tuple is: ", t1 + t2)
print("Maximum number in ", t1, " is: ", max(t1))
print("Minimum number in ", t1, " is: ", min(t1))
Program 4: Write a function that takes a sentence as input from the user and
calculates the frequency of each letter. Use a variable of dictionary type to maintain
the count.

# using naive method to get count


# of each element in string
def all_freq(str1):
frequency = {}
for i in str1:
print(i)
if i in frequency:
frequency[i] += 1
else:
frequency[i] = 1
return frequency

# Main function
s1 = input("Enter a string: ")
# printing result
print("Count of all characters in " , s1 , " is :\n " , all_freq(s1))
PART B
Program 1: Program to create a class Employee with empno, name, depname,
designation, age and salary and perform the following function
a. To accept details of N employees
b. To display details of all the employees
c. To search for an employee among all employees and display the details of that
employee.

#class definition
class Emp:
#class constructor for initialization
def __init__(self):
self.sal = None
self.age = None
self.des = None
self.d_name = None
self.e_name = None
self.eno = None

#User defined function to get data


def get_data(self):
self.eno = int(input("Enter the employee ID: "))
self.e_name = input("Enter the employee name: ")
self.d_name = input("Enter employee department: ")
self.des = input("Enter employee designation: ")
self.age = int(input("Enter employee age: "))
self.sal = float(input("Enter employee salary: "))
print()

#User defined function to display data


def showdata(self):
print(self.eno, "\t", self.e_name, "\t", self.d_name, "\t",
self.des, "\t", self.age, "\t", self.sal)

#User defined function to search data


def search(self, e_no):
if e_no == self.eno:
return True
else:
return False

#lst is the list used to store employee data


lst = []
while True:
print("\nMENU\n1. Enter employee details\n2. Display all employee
details\n3. Search employee details\n4. Exit")
ch = int(input("Enter your choice: "))
if ch == 1:
n = int(input("Enter the number of employees: "))
for i in range(n):
#e in the object of Emp class
e = Emp()
e.get_data()
lst.append(e)
elif ch == 2:
if len(lst) == 0:
print("No employee details found! Try again")
else:
print("\nAll employee details")
for i in lst:
i.showdata()
elif ch == 3:
e_num = int(input("Enter employee id to search: "))
for i in lst:
found = i.search(e_num)
if found:
print("Employee details found:")
i.showdata()
break
else:
print("Employee details not found!")
else:
print("ID not found! Try again")
elif ch == 4:
break
else:
print("Invalid choice!! Try again.")
Program 2: Program to create a class Rectangle with data members’ length and
width and a method which will compute the area and perimeter of rectangle. Inherit
a class Box that contains additional method volume. Override the perimeter method
to compute perimeter of a Box. Display details Rectangle and Box
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

def compute_area(self):
area = self.length * self.width
return area

def compute_perimeter(self):
perimeter = 2 * (self.length + self.width)
return perimeter

class Box(Rectangle):

def compute_volume(self):
volume = self.length ** 3
return volume

l = float(input('Enter the Length: '))


w = float(input('Enter the Width: '))
# create object
b = Box(l,w)
# area and perimeter of the rectangle object
print("Area of Rectangle = ", area)
area = b.compute_area()
print("Perimeter of Rectangle = ", perimeter)
perimeter = b.compute_perimeter()
# area and perimeter of the box object
print("Perimeter of Box = ", perimeter)
perimeter = b.compute_perimeter()
print("Volume of Box = ", volume)
volume = b.compute_volume()
Program 3: Program using user defined exception class that will ask the user to
enter a number until he guesses a stored number correctly. To help them figure it
out, a hint is provided whether their guess is greater than or less than the stored
number using user defined exceptions.
class SmallValueError(Exception):
"""Raised when the input value is too small"""
pass

class LargeValueError(Exception):
"""Raised when the input value is too large"""
pass

# you need to guess this number


number = 10
# user guesses a number until he/she gets it right
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise SmallValueError
elif i_num > number:
raise LargeValueError
break
except SmallValueError:
print("This value is too small, try again!")
print()
except LargeValueError:
print("This value is too large, try again!")
print()

print("Congratulations! You guessed it correctly.")


Program 4: Write a Python program to
a. Find the sequences of one upper case letter followed by lower case letters.
b. Match a word containing 'z'.
c. Match a string that contains only upper and lowercase letters, numbers, and
underscores.
d. Remove leading zeros from an IP address.
import re

def text_match1(text):
patterns = '[A-Z]+[a-z]+$'
word = re.search(patterns, text)
if word:
return 'Match found \n'
else:
return 'Match not found\n'

def text_match2(text):
# text that contains 'z'
regex = re.compile("z+\w*", re.IGNORECASE)
# The findall() method returns all matching strings of the regex
pattern
match_object = regex.findall(text)
# If length of match_object is not equal to zero then it contains
matched string
if len(match_object) > 0:
# looping through the list
for word in match_object:
print("The word with the z is: ", word)
else:
print("No match\n")

def text_match3(text):
patterns = '^[a-zA-Z0-9_]*$'
if re.search(patterns, text):
return 'Found a match!\n'
else:
return 'Not matched!\n'

def text_match4(ip):
string = re.sub(r'\b0+(\d)', r'\1', ip)
return string

while True:
print("Menu-\n"
"1. Find the sequences of one upper case letter followed by
lower case letters.\n"
"2. Match a word containing 'z'\n"
"3. Match a string that contains only upper and lowercase
letters, numbers, and underscores\n"
"4. Remove leading zeros from an IP address \n"
"5. Exit \n")
x = int(input("Enter Your Choice : "))
if x == 1:
str1 = input("Enter the String:")
print(text_match1(str1))
elif x == 2:
str2 = input("Enter the String:")
text_match2(str2)
elif x == 3:
str3 = input("Enter the String:")
print(text_match3(str3))
elif x == 4:
str4 = input("Enter the IP address:")
print(text_match4(str4))
elif x == 5:
break
else:
print("Wrong Input!")
Part C
Program 1: GUI program to design a Simple Calculator

# import everything from tkinter module


from tkinter import *

# globally declare the expression variable


expression = ""

# Function to update expression in the text entry box


def press(num):
# point out the global expression variable
global expression

# concatenation of string
expression = expression + str(num)

# update the expression by using set method


equation.set(expression)

# Function to evaluate the final expression


def equalpress():
# Try and except statement is used for handling the errors like zero
division error etc.

# Put that code inside the try block which may generate the error
try:

global expression

# eval function evaluate the expression and str function convert


the resultinto string
total = str(eval(expression))

equation.set(total)

# initialize the expression variable by empty string


expression = ""

# if error is generated then handle by the except block


except EXCEPTION:
equation.set(" error ")
expression = ""

# Function to clear the contents text entry box


def clear():
global expression
expression = ""
equation.set("")

# Driver code
if __name__ == "__main__":
# create a GUI window
gui = Tk()

# set the background colour of GUI window


gui.configure(background="white")

# set the title of GUI window


gui.title("Simple Calculator")

# set the configuration of GUI window


gui.geometry("270x150")

# StringVar() is the variable class. we create an instance of this


class
equation = StringVar()

# create the text entry box for showing the expression .


expression_field = Entry(gui, textvariable=equation)

# grid method is used for placing the widgets at respective positions


table like structure .
expression_field.grid(columnspan=4, ipadx=70)

# create a Buttons and place at a particular location inside the root


window. when user press the button, the command or function affiliated to
that button is executed .
button1 = Button(gui, text=' 1 ', fg='black', bg='white',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)

button2 = Button(gui, text=' 2 ', fg='black', bg='white',


command=lambda: press(2), height=1, width=7)
button2.grid(row=2, column=1)

button3 = Button(gui, text=' 3 ', fg='black', bg='white',


command=lambda: press(3), height=1, width=7)
button3.grid(row=2, column=2)

button4 = Button(gui, text=' 4 ', fg='black', bg='white',


command=lambda: press(4), height=1, width=7)
button4.grid(row=3, column=0)

button5 = Button(gui, text=' 5 ', fg='black', bg='white',


command=lambda: press(5), height=1, width=7)
button5.grid(row=3, column=1)

button6 = Button(gui, text=' 6 ', fg='black', bg='white',


command=lambda: press(6), height=1, width=7)
button6.grid(row=3, column=2)
button7 = Button(gui, text=' 7 ', fg='black', bg='white',
command=lambda: press(7), height=1, width=7)
button7.grid(row=4, column=0)

button8 = Button(gui, text=' 8 ', fg='black', bg='white',


command=lambda: press(8), height=1, width=7)
button8.grid(row=4, column=1)

button9 = Button(gui, text=' 9 ', fg='black', bg='white',


command=lambda: press(9), height=1, width=7)
button9.grid(row=4, column=2)

button0 = Button(gui, text=' 0 ', fg='black', bg='white',


command=lambda: press(0), height=1, width=7)
button0.grid(row=5, column=0)

plus = Button(gui, text=' + ', fg='black', bg='white',


command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)

minus = Button(gui, text=' - ', fg='black', bg='white',


command=lambda: press("-"), height=1, width=7)
minus.grid(row=3, column=3)

multiply = Button(gui, text=' * ', fg='black', bg='white',


command=lambda: press("*"), height=1, width=7)
multiply.grid(row=4, column=3)

divide = Button(gui, text=' / ', fg='black', bg='white',


command=lambda: press("/"), height=1, width=7)
divide.grid(row=5, column=3)

equal = Button(gui, text=' = ', fg='black', bg='white',


command=equalpress, height=1, width=7)
equal.grid(row=5, column=2)

clear = Button(gui, text='Clear', fg='black', bg='white',


command=clear, height=1, width=7)
clear.grid(row=5, column=1)

Decimal = Button(gui, text='.', fg='black', bg='white',


command=lambda: press('.'), height=1, width=7)
Decimal.grid(row=6, column=0)
# start the GUI
gui.mainloop()
Program 2: Create a GUI to input Principal amount, rate of interest and number of
years, Calculate Compound interest. When button submit is pressed Compound
interest should be displayed in a textbox. When clear button is pressed all contents
should be cleared.
# import all classes / functions from the tkinter
from tkinter import *

# Function for clearing the contents of all entry boxes


def clear_all():
# whole content of entry boxes is deleted
principle_field.delete(0, END)
rate_field.delete(0, END)
time_field.delete(0, END)
compound_field.delete(0, END)

# set focus on the principle_field entry box


principle_field.focus_set()

# Function to find compound interest


def calculate_ci():
# get a content from entry box
principle = int(principle_field.get())

rate = float(rate_field.get())

time = int(time_field.get())

# Calculates compound interest


ci = principle * (pow((1 + rate / 100), time))

# insert method inserting the value in the text entry box.


compound_field.insert(20, ci)

# Driver code
if __name__ == "__main__":
# Create a GUI window
root = Tk()

# Set the background colour of GUI window


root.configure(background='white')

# Set the configuration of GUI window


root.geometry("350x250")

# set the name of tkinter GUI window


root.title("Compound Interest Calculator")

# Create a Principle Amount : label


label1 = Label(root, text="Principle Amount(Rs) : ", fg='black')
# Create a Rate : label
label2 = Label(root, text="Rate(%) : ", fg='black')

# Create a Time : label


label3 = Label(root, text="Time(years) : ", fg='black')

# Create a Compound Interest : label


label4 = Label(root, text="Compound Interest : ", fg='black')

# grid method is used for placing the widgets at respective positions


in table like structure .

# padx keyword argument used to set padding along x-axis .


# pady keyword argument used to set padding along y-axis .
label1.grid(row=1, column=0, padx=10, pady=10)
label2.grid(row=2, column=0, padx=10, pady=10)
label3.grid(row=3, column=0, padx=10, pady=10)
label4.grid(row=5, column=0, padx=10, pady=10)

# Create an entry box for filling or typing the information.


principle_field = Entry(root)
rate_field = Entry(root)
time_field = Entry(root)
compound_field = Entry(root)

# grid method is used for placing the widgets at respective positions


in table like structure .

# padx keyword argument used to set padding along x-axis .


# pady keyword argument used to set padding along y-axis .
principle_field.grid(row=1, column=1, padx=10, pady=10)
rate_field.grid(row=2, column=1, padx=10, pady=10)
time_field.grid(row=3, column=1, padx=10, pady=10)
compound_field.grid(row=5, column=1, padx=10, pady=10)

# Create a Submit Button and attached to calculate_ci function


button1 = Button(root, text="Submit", fg="black",
command=calculate_ci)

# Create a Clear Button and attached to clear_all function


button2 = Button(root, text="Clear", fg="black", command=clear_all)

button1.grid(row=4, column=1, pady=10)


button2.grid(row=6, column=1, pady=10)

# Start the GUI


root.mainloop()
Program 3: Create a table student table (regno, name and marks in 3 subjects) using
MySQL and perform the followings
a. To accept the details of students and store it in database.
b. To display the details of all the students.
c. Delete particular student record using regno.
d. import MySQLdb

conn = MySQLdb.connect(host='localhost', database='world', user='root',


password='Admin@123')
cursor = conn.cursor()
while True:
print("Operations Used...")
print("1. Accept student details\n"
"2. Display Student Details\n"
"3. Delete Details of Student\n"
"4. Exit")
ch = int(input("Enter your choice:"))
if ch == 1:
n = int(input("Enter how many students details?"))
for i in range(n):
regno = int(input("Enter the register number:"))
name = input("Enter the name:")
m1 = int(input("Enter M1:"))
m2 = int(input("Enter M2:"))
m3 = int(input("Enter M3:"))
str = "insert into
student1(regno,name,m1,m2,m3)values('%d','%s','%d','%d','%d')"
args = (regno, name, m1, m2, m3)
try:
cursor.execute(str % args)
conn.commit()
print("1 row inserted...")
except:
print("Register Number already exists")
conn.rollback()
elif ch == 2:
cursor.execute("select *from student1")
row = cursor.fetchone()
if row is not None:
while row is not None:
print(row)
row = cursor.fetchone()
else:
print("No records found")
elif ch == 3:
rno = int(input("Enter the register number of the student to be
deleted: "))
str = "delete from student1 where regno='%d'"
args = (rno)
try:
row = cursor.execute(str % args)
if row == 1:
conn.commit()
print("1 row deleted...")
else:
print("Record Not found")
except:
conn.rollback()
elif ch == 4:
break
else:
print("Wrong Choice")

cursor.close()
conn.close()

OUTPUT:
mysql> create table student1(regno int primary key, name varchar (15), m1 int, m2
int, m3 int);
Query OK, 0 rows affected (0.03 sec)
Operations Used...
1. Accept student details
2. Display Student Details
3. Delete Details of Student
4. Exit
Enter your choice:1
Enter how many students details?2
Enter the register number:111
Enter the name: Ram
Enter M1:90
Enter M2:89
Enter M3:99
1 row inserted...
Enter the register number:222
Enter the name: John
Enter M1:80
Enter M2:88
Enter M3:77
1 row inserted...
Operations Used...
1. Accept student details
2. Display Student Details
3. Delete Details of Student
4. Exit
Enter your choice:2
(111, ‘Ram’, 90, 89, 99)
(222, ‘John’, 80, 88, 77)
Operations Used...
1. Accept student details
2. Display Student Details
3. Delete Details of Student
4. Exit
Enter your choice:1
Enter how many students details?1
Enter the register number:111
Enter the name:Kiran
Enter M1:56
Enter M2:78
Enter M3:99
Register Number already exists
Operations Used...
1. Accept student details
2. Display Student Details
3. Delete Details of Student
4. Exit
Enter your choice:3
Enter the register number of the student to be deleted: 555
Record Not found
Operations Used...
1. Accept student details
2. Display Student Details
3. Delete Details of Student
4. Exit
Enter your choice:3
Enter the register number of the student to be deleted: 222
1 row deleted...
Operations Used...
1. Accept student details
2. Display Student Details
3. Delete Details of Student
4. Exit
Enter your choice:2
(111, ‘Ram’, 90, 89, 99)
Operations Used...
1. Accept student details
2. Display Student Details
3. Delete Details of Student
4. Exit
Enter your choice:4
Program 4: Create a table employee (empno, name and salary) using MySql and
perform the
followings
a. To accept the details of employees and store it in database.
b. To display the details of a specific employee
c. To display employee details whose salary lies within a certain range
d. import MySQLdb

conn = MySQLdb.connect(host='localhost', database='world', user='root',


password='Admin@123')
cursor = conn.cursor()
while True:
print("Operations Used...")
print("1. Accept Employee details\n"
"2. Display Details of a specific Employee\n"
"3. Display employee details whose salary lies within a
certain range\n"
"4. Exit")
ch = int(input("Enter your choice"))
if ch == 1:
n = int(input("Enter how many employees details?:"))
for i in range(n):
empno = int(input("Enter the employee number:"))
name = input("Enter the name:")
salary = int(input("Enter Salary:"))
str = "insert into
employee(empno,name,salary)values('%d','%s','%d')"
args = (empno, name, salary)
try:
cursor.execute(str % args)
conn.commit()
print("1 row inserted...")
except:
print("Employee Number already exists")
conn.rollback()
elif ch == 2:
eno = int(input("Enter the employee number of the employee to
display the details: "))
str = "select *from employee where empno='%d'"
args = (eno)
cursor.execute(str % args)
row = cursor.fetchone()
if row is not None:
while row is not None:
print(row)
row = cursor.fetchone()
else:
print("No records found")
elif ch == 3:
cursor.execute("select *from employee where salary between
20000 and 50000")
row = cursor.fetchone()
if row is not None:
while row is not None:
print(row)
row = cursor.fetchone()
else:
print("No records found")
elif ch == 4:
break
else:
print("Wrong Choice")

cursor.close()
conn.close()

Output:
mysql> create table employee (empno int primary key, name varchar (15), salary
int);
Query OK, 0 rows affected (0.03 sec)
Operations Used...
1. Accept Employee details
2. Display Details of a specific Employee
3. Display employee details whose salary lies within a certain range
4. Exit
Enter your choice:1
Enter how many employeesdetails?2
Enter the employee number:111
Enter the name: Ram
Enter Salary:60000
1 row inserted...
Enter the employee number:222
Enter the name: John
Enter Salary:20000
1 row inserted...
Operations Used...
1. Accept Employee details
2. Display Details of a specific Employee
3. Display employee details whose salary lies within a certain range
4. Exit
Enter your choice:2
Enter the employee number of the employee to display the details: 222
(222, ‘John’, 20000)
Operations Used...
1. Accept Employee details
2. Display Details of a specific Employee
3. Display employee details whose salary lies within a certain range
4. Exit
Enter your choice:2
Enter the employee number of the employee to display the details: 555
No records found
Operations Used...
1. Accept Employee details
2. Display Details of a specific Employee
3. Display employee details whose salary lies within a certain range
4. Exit
Enter your choice:3
(222, ‘John’, 20000)
Operations Used...
1. Accept Employee details
2. Display Details of a specific Employee
3. Display employee details whose salary lies within a certain range
4. Exit
Enter your choice:4

You might also like