CA Lab-V LAB on Python Programming.docx (2)
CA Lab-V LAB on Python Programming.docx (2)
if( choice == 1 ):
for x in range(1,8,2):
print(x)
elif( choice == 2 ):
count=1;
print(count)
count+=2;
else:
print( "Ok" )
Output: -
1. For Loop
2. While Loop
1
Assignment 2. Develop programs to learn different types of structures (list, dictionary,
tuples) in python
2
print(my_list.index(10)) #find index of element that occurs first
print(my_list.count(10)) #find count of the element
print(sorted(my_list)) #print sorted list but not c
elif( choice == 2 ):
my_dict = {1: 'Python', 2: 'Java'} #dictionary with elements
print(my_dict)
my_dict = {'First': 'Python', 'Second': 'Java'}
print(my_dict)
my_dict['Second'] = 'C++' #changing element
print(my_dict)
my_dict['Third'] = 'Ruby' #adding key-value pair
print(my_dict)
my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'}
a = my_dict.pop('Third') #pop element
print('Value:', a)
print('Dictionary:', my_dict)
b = my_dict.popitem() #pop the key-value pair
print('Key, value pair:', b)
print('Dictionary', my_dict)
my_dict.clear() #empty dictionary
print(my_dict)
my_dict = {'First': 'Python', 'Second': 'Java'}
print(my_dict['First']) #access elements using keys
print(my_dict.get('Second'))
my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'}
print(my_dict.keys()) #get keys
print(my_dict.values()) #get values
print(my_dict.items()) #get key-value pairs
elif( choice == 3 ):
my_tuple = (1, 2, 3) #create tuple
print(my_tuple)
my_tuple2 = (1, 2, 3, 'edureka') #access elements
for x in my_tuple2:
print(x)
3
print(my_tuple2)
print(my_tuple2[0])
print(my_tuple2[:])
print(my_tuple2[3][4])
my_tuple = (1, 2, 3)
my_tuple = my_tuple + (4, 5, 6) #add elements
print(my_tuple)
my_tuple = (1, 2, 3, ['hindi', 'python'])
my_tuple[3][0] = 'english'
print(my_tuple)
print(my_tuple.count(2))
print(my_tuple.index(['english', 'python']))
else:
print( "Ok" )
Output: -
4
Assignment 3. Develop programs to learn concept of functions scoping, recursion and
list mutability.
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
5
print(my_list)
my_list.insert(1, 'insert_example') #add element
print(my_list)
del my_list[5] #delete element at index 5
print(my_list)
my_list.remove('example') #remove element with value
print(my_list)
a = my_list.pop(1) #pop element from list
print('Popped Element: ', a, ' List remaining: ', my_list)
my_list.clear() #empty the list
print(my_list)
else:
print( "Ok" )
Output: -
6
Assignment 4. Develop programs to understand object oriented programming using
python.
c = Child()
c.childMethod()
c.parentMethod()
c.setAttr(200)
c.getAttr()
Output:-
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200
7
Assignment 5. Develop programs for data structure algorithms using python –
searching, sorting and hash tables.
if lys[i] == element:
return i
return -1
first = 0
last = len(lys)-1
index = -1
mid = (first+last)//2
if lys[mid] == val:
index = mid
else:
if val<lys[mid]:
last = mid -1
else:
first = mid +1
return index
def bubblesort(list):
8
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
middle = len(unsorted_list) // 2
left_list = unsorted_list[:middle]
right_list = unsorted_list[middle:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
def merge(left_half,right_half):
res = []
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
9
if len(left_half) == 0:
else:
return res
def insertionSort(arr):
if (n := len(arr)) <= 1:
return
key = arr[i]
j = i-1
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
min_index = ind
10
min_index = j
if( choice == 1 ):
print(LinearSearch([1,2,3,4,5,2,1], 5))
elif( choice == 2 ):
print(BinarySearch([10,20,30,40,50], 40))
elif( choice == 3 ):
list = [19,2,31,45,6,11,121,27]
bubblesort(list)
print(list)
elif( choice == 4 ):
print(merge_sort(unsorted_list))
11
elif( choice == 5 ):
insertionSort(arr)
print(arr)
elif( choice == 6 ):
size = len(arr)
selectionSort(arr, size)
print(arr)
elif( choice == 7 ):
# Declare a dictionary
12
print ("dict['School']: ", dict['School'])
else:
print( "Ok" )
Output:-
Select your Choice:
1. Linear Search
2. Binary Search
3. Bubble Sort
4. Merge Sort
5. Insertion Sort
6. Selection Sort
7. Hash Table
13
Assignment 6. Develop programs to learn regular expressions using python.
import re
#Return a list containing every occurrence of "ai":
txt1 = "The rain in Spain"
x1 = re.findall("ai", txt1)
print(x1)
#Search for an upper case "S" character in the beginning of a word, and print the word:
txt6 = "The rain in Spain"
x6 = re.search(r"\bS\w+", txt6)
print(x6.group())
14
Output:-
['ai', 'ai']
The first white-space character is located in position: 3
['The', 'rain', 'in', 'Spain']
The9rain9in9Spain
<re.Match object; span=(5, 7), match='ai'>
Spain
15
Assignment 7. Demonstrate the concept of exception handling using try/except/else
Statement, Unified try/except/finally, try/finally Statement, raise Statement, assert
Statement, catch multiple specific exceptions
# Constructor or Initializer
def __init__(self, value):
self.value = value
16
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-1-dfedc9c43237> in <module>
38 x = "hello"
39 #if condition returns False, AssertionError is raised:
---> 40 assert x == "goodbye", "x should be 'hello'"
17
Assignment 8. Demonstrate the concept of String-Based Exceptions, Class-Based
Exceptions and Nesting Exception handlers.
#String-Based Exceptions
try:
print(1 + '3')
except Exception as e:
error_message = str(e)
print(error_message)
print(type(error_message))
#Class-Based Exceptions
class LowAgeError(Exception):
def __init__(self):
pass
def __str__(self):
return 'The age must be greater than 18 years'
class Employee:
def __init__(self, name, age):
self.name = name
if age < 18:
raise LowAgeError
else:
self.age = age
def display(self):
print('The name of the employee: ' + self.name + ', Age: ' + str(self.age) +' Years')
try:
e1 = Employee('Subhas', 25)
e1.display()
e2 = Employee('Anupam', 12)
e1.display()
except LowAgeError as e:
print('Error Occurred: ' + str(e))
#Nested
x = 10
y=0
try:
print("outer try block")
try:
print("nested try block")
print(x / y)
except TypeError as te:
print("nested except block")
18
print(te)
except ZeroDivisionError as ze:
print("outer except block")
print(ze)
Output: -
unsupported operand type(s) for +: 'int' and 'str'
<class 'str'>
The name of the employee: Subhas, Age: 25 Years
Error Occurred: The age must be greater than 18 years
outer try block
nested try block
outer except block
division by zero
19
Assignment 9. Demonstrate implementation of the Anonymous Function Lambda.
Output: -
Area of the triangle: 408.0
20
Assignment 10. Demonstrate implementation functional programming tools such as
filter and reduce
series = [23,45,57,39,1,3,95,3,8,85]
result = filter (lambda m: m > 29, series)
print('All the numbers greater than 29 in the series are :',list(result))
Output: -
All the numbers greater than 29 in the series are : [45, 57, 39, 95, 85]
Output: - The total sum of all the elements in the list is: 196
21
Assignment 11. Demonstrate the Module Creation, Module usage.
22
Assignment 12. Demonstrate image insertion in python.
Output: -
23
Assignment 13. Demonstrate use of DataFrame method and use of .csv files.
Output:-
24
Assignment 14. Develop programs to learn GUI programming using Tkinter
base = Tk()
base.geometry('600x600')
base.title("Registration Form")
l1 = Label(base, text="Enter Name",width=20,font=("bold", 10))
l1.place(x=90,y=55)
t1 = Entry(base)
t1.place(x=220,y=55)
radio=IntVar()
l2= Label(base, text="Select Gender",width=20,font=("bold", 10))
l2.place(x=94,y=93)
r1 = Radiobutton(base, text="Male", value=1,variable=radio)
r1.place(x=220,y=93)
r2 = Radiobutton(base, text="Female", value=2,variable=radio)
r2.place(x=280,y=93)
25
chk1=IntVar()
chk2=IntVar()
chk3=IntVar()
l4= Label(base, text="Select Color",width=20,font=("bold", 10))
l4.place(x=90,y=300)
c1 = Checkbutton(base,text = "Red",width = 20, onvalue=1,variable=chk1)
c1.place(x=220,y=300)
c2 = Checkbutton(base,text = "Green",width = 20,onvalue=2,variable=chk2)
c2.place(x=340,y=300)
c3 = Checkbutton(base,text = "Blue",width = 20,onvalue=3,variable=chk3)
c3.place(x=460,y=300)
Output:-
Name= abc
Gender=Male
Color= Red Green
MCA-I
26
Assignment 15. Create a simple web application using Flask.
if __name__=='__main__':
app.run()
OUTPUT:-
27
Assignment 16. Create Simple Django Framework
Step1: Open Anaconda Navigator, Click on Environments, Click on Create, Give name
Django2
Step2: Tick on Python package and select version 3.7 or above, Click on Create button.
Step3: Click on Home, select Applications on as Django2, Launch Jupyter Notebook.
Step4: Take New Python3-Install following packages one by one and every time restart
kernel.
pip install django
pip install django-bootstrap4
pip install django-crispy-forms
28
Step5: Select Django2-select Installed-Update Index and see installed packages as follows.
29
Assignment 17. Demonstrate Database connectivity using MySql.
def insert_data():
id = entry_id.get()
30
name = entry_name.get()
email = entry_email.get()
query = "INSERT INTO student (id,name, email) VALUES (%s, %s,%s)"
values = (id,name, email)
execute_query(query, values)
def update_data():
id = entry_id.get()
name = entry_name.get()
email = entry_email.get()
query = "UPDATE student SET name = %s, email = %s WHERE id = %s"
values = (name, email,id)
execute_query(query, values)
def delete_data():
name = entry_name.get()
query = "DELETE FROM student WHERE name = %s"
values = (name,)
execute_query(query, values)
def select_data():
try:
with connect(**db_config) as connection:
query = "SELECT * FROM student"
cursor = connection.cursor()
cursor.execute(query)
rows = cursor.fetchall()
for row in rows:
print(row) # You can modify this to display the data in your Tkinter application
except Error as e:
print(f"Error executing query: {e}")
31
# Tkinter application setup
root = tk.Tk()
label_id = tk.Label(root, text="ID")
label_id.grid(row=0, column=0)
entry_id = tk.Entry(root)
entry_id.grid(row=0, column=1)
entry_name = tk.Entry(root)
entry_name.grid(row=1, column=1)
entry_email = tk.Entry(root)
entry_email.grid(row=2, column=1)
32
OUTPUT:-
33