0% found this document useful (0 votes)
76 views31 pages

PP LabManual BH23 24batch

Uploaded by

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

PP LabManual BH23 24batch

Uploaded by

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

BVRIT HYDERABAD

College of Engineering for Women (UGC Autonomous)


The Temple for Women Empowerment & Human Values

B.Tech
I Year/ II Sem(BH23)

PYTHON PROGRAMMING LAB MANUAL


INSTITUTE VISION & MISSION

VISION

To emerge as the best among the institutes of technology and research in the country dedicated to
the cause of promoting quality technical education.

MISSION

At BVRITH, we strive to

 Achieve academic excellence through innovative learning practices.


 Enhance intellectual ability and technical competency for a successful career.
 Encourage research and innovation.
 Nurture students towards holistic development with emphasis on leadership skills. life
skills and human values.
CSE DEPARTMENT VISION & MISSION

VISION
Develop women as technocrats, researchers and entrepreneurs in the field of Computer Science
and Engineering.

MISSION

M1: To impart quality education in Computer Science and Engineering by means of learning
techniques and value-added courses.

M2: To inculcate professional excellence and research culture by encouraging projects in


cutting-edge technologies through industry interactions.

M3: To build leadership skills, ethical values and teamwork among the students.

M4: To strengthen the collaboration of department and industry through internships, mentorships
and professional body activities.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

After three to six years of graduation, the graduates of this program will be able to:

PEO-1: Develop innovative computing products by utilizing strong technical proficiency and
critical thinking.

PEO-2: Productively engage in research by practicing basic principles grounded in allied areas
of Computer Science and Engineering.

PEO-3: Adapt the emerging technologies to contribute technical innovations for progressive
development.

PEO-4: Demonstrate professionalism, ethical attitude, teamwork and leadership skills with
lifelong learning in the career.

PROGRAM SPECIFIC OUTCOMES (PSOs)

The graduates of this program will be able to:

PSO-1 : Ability to apply learned skills to build optimized solutions pertaining to Computer
& Communication Systems, Data Processing and Artificial Intelligence.

PSO-2 : Employ standard strategies and practices in project development using FOSS
(Free Open Source Software).
CSE (AIML) DEPARTMENT VISION & MISSION

VISION
Produce competent technocrats, researchers, and entrepreneurs in Artificial Intelligence &
Machine Learning to build an ecosystem that significantly contributes to the nation
MISSION

M1: To impart skills through various learning methodologies and value-added courses to be
technically competent.
M2: To build the research culture through participations in innovative projects and publications
M3: To inculcate ethics, leadership skills, life skills and lifelong learning
M4: To expose the students to real time environment by internships and mentorships through
collaborations with industries and premier institutions.

Program Educational Objectives (PEOs)

After three to six years of graduation, the graduates of this program will be able to:

PEO–1: Adapt emerging technologies to contribute to the technical innovations for the
progressive development in their respective fields.
PEO–2: Productively engage in multidisciplinary research areas by applying the basic principles
of engineering sciences.
PEO–3: Demonstrate strong technical skills to bring out novel designs/products to address the
social & environmental issues.

PEO-4: Exhibit professional attitude, teamwork and practice code of ethics


CONTENTS

S.No Contents Page No


1 Syllabus 6
2 Instructions to students 9
3 Programs 11
4 Viva Questions 27
B.Tech. I Year II Semester
Course Code Course Title L T P Credits
CS206ES Python Programming Laboratory 012 2

Course Description: This Course Covers Installation procedure of python and packages. Course
focuses on implementation of different control structures, data structures and Files in Python. It
also helps to implement GUI applications using TKinter.

Course Outcomes: After completion of this course, the students will be able to
C206.1: Build basic programs using fundamental programming constructs.
C206.2: Explore Strings, Lists, Tuples and Dictionaries in Python
C206.3: Develop reusable code and GUI application using standard Library.
C206.4: Implement File I/O and Digital Logic Gates using Python

LIST OF EXPERIMENTS
Cycle 1:
Week - 1:
1. (i) Use a web browser to go to the Python website http://python.org. This page contains
information about Python and links to Python-related pages, and it gives you the ability
to search the Python documentation.
(ii) Start the Python interpreter and type help() to start the online help utility.

2. Start a Python interpreter and use it as a Calculator.

(i) Write a program to calculate compound interest when principal, rate and number of
periods are given.
(ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points.

3. Read name, address, email and phone number of a person through keyboard and print the
details.

Week - 2:
1. Find the Euclidean distance with the given values and check the validity of values to find
the distance.
2. Generate a random number between 1-10 and ask the user to guess the number. Give
chance for 3 times. If guessed correctly then congratulate otherwise print message as
sorry.
3. Accept a string and generate the combinations of string until the source string doesn’t
repeated.
4. Generate prime numbers of Fibonacci series between 1-50.
Week - 3:
1. (i) Write a program to convert a list and tuple into arrays.
(ii) Write a program to find common values between two arrays.
2. Write a program to add comma separators in a given big number as per the standard
American convention. Ex: i/p: 100000000 o/p: 100,000,000.

3. Write a program to convert given formula 3X+4Y as 3*X+4*Y and 3(X+Y) as


3*X+3*Y etc.

Week - 4:
1. Write a function called is_sorted that takes a list as a parameter and returns True if the list
is sorted in ascending order and False otherwise.

2. Write a function called has_duplicates that takes a list and returns True if there is any
element that appears more than once. It should not modify the original list.

3. (i) Write a function called remove_duplicates that takes a list and returns a new list with
only the unique elements from the original. Hint: they don’t have to be in the same order.
(ii) The wordlist I provided, words.txt, doesn’t contain single letter words. So you might
want to add “I”, “a”, and the empty string.
(iIi) Write a python code to read dictionary values from the user. Construct a function to
invert its content. i.e., keys should be values and values should be keys.
4. (i) Add a comma between the characters. If the given word is 'Apple', it should become
'A,p,p,l,e'.
(ii) Remove the given word in all the places in a string?
(iii) Write a function that takes a sentence as an input parameter and replaces the first
letter of every word with the corresponding upper case letter and the rest of the
letters in the word by corresponding letters in lower case without using a built-in
function?
5. Writes a recursive function that generates all binary strings of n-bit length.

Week - 5:
1. (i) Write a python program that defines a matrix and prints.
(ii) Write a python program to perform addition of two square matrices.
(iii) Write a python program to perform multiplication of two square matrices
2. How do you make a module? Give an example of construction of a module using
different geometrical shapes and operations on them as its functions.

3. Use the structure of exception handling all general purpose exceptions.


Cycle2:
Week- 6:
1. (i)Writeafunctioncalleddraw_rectanglethattakesaCanvasandaRectangleas arguments and
draws a representation of the Rectangle on the Canvas.
(ii) Add an attribute named color to your Rectangle objects and modify draw_rectangle
so that it uses the color attribute as the fill color.
(iii)Write a function called draw_point that takes a Canvas and a Point as arguments and
draws a representation of the Point on the Canvas.
(iv)Define a new class called Circle with appropriate attributes and instantiate a few
Circle objects. Write a function called draw_circle that draws circles on the canvas.
2. Write a Python program to demonstrate the usage of Method Resolution Order (MRO) in
multiple levels of Inheritances.
3. Write a python code to read a phone number and email-id from the user and validate it
for correctness
Week- 7:
1. Write a Python code to merge two given file contents in to a third file.
2. WriteaPythoncodetoopenagivenfileandconstructafunctiontocheckforgiven words present
in it and display on found.
3. Write a Python code to Read text from a text file, find the word with most number of
occurrences.
4. Write a function that reads a file file1 and displays the number of words, number of
vowels, blank spaces, lower case letters and uppercase letters.
Week- 8:
1. Import Numpy, Plotpy and Scipy and explore their functionalities.
2. Install Numpy package with pip and explore it.
3. Write a program to implement Digital Logic Gates–AND, OR, NOT, EX-OR.
4. Write a program to implement Half Adder, Full Adder,and Parallel Adder.
5. Write a GUI program to create a window wizard having two text labels, two text fields
and two buttons as Submit and Reset.
INSTRUCTIONSTOSTUDENTS

On entering the lab you should make an entry in the log book available with the details regarding
student name, roll no, system no and signature.

Student must bring Observation note book for every lab session. Observation book should be
duly signed by your faculty, failing which your report will not be graded.

Student must complete all experimental programs allotted during the session.

Student should shut down the system properly and leave the lab neat and tidy.

GRADING

For practical subjects there shall be a Continuous Internal Evaluation (CIE) during the semester
for 40 marks and 60 marks for semester end examination.
Out of the 40 marks for internal evaluation:
1. A write-up on day-to-day experiment in the laboratory (in terms of aim, components /
procedure, expected outcome) which shall be evaluated for 10 marks
2. 10 marks for viva-voce (or) tutorial (or) case study (or) application (or) poster presentation of
the course concerned.
3. Internal practical examination conducted by the laboratory teacher concerned shall be
evaluated for 10 marks.
4. The remaining 10 marks are for Laboratory Report / Project and Presentation, which consists
of the Design (or) Software / Hardware Model Presentation (or) App Development (or)
Prototype Presentation submission which shall be evaluated after completion of laboratory
Course and before semester end practical examination.

The Semester End Examination shall be conducted with an external examiner and the laboratory
teacher. The external examiner shall be appointed by the Controller of Examinations / Chief
Superintendent on the recommendation of BoS chairman of the concerned department.

In the Semester End Examination held for 3 hours, total 60 marks are divided and allocated as
shown below:
1. 10 marks for write-up
2. 15 for experiment / program
3. 15 for evaluation of results
4. 10 marks for presentation on another experiment / program in the same laboratory course and
5. 10 marks for viva-voce on concerned laboratory course.

The Student, in each subject, shall have to earn 35% of marks (i.e. 14 marks out of 40 marks) in
CIE, 35% of marks (i.e. 21 marks out of 60) in SEE and overall 40% of marks (i.e. 40 marks out
of 100 marks) both CIE and SEE marks put together.

The student is eligible to write Semester End Examination of the concerned subject, if the
student scores ≥ 35% (14 marks) of 40 Continuous Internal Examination (CIE) marks.

In case, the student appears for Semester End Examination (SEE) of the concerned subject but
not scored minimum 35% of CIE marks (14 marks out of 40 internal marks), her performance in
that subject in SEE shall stand cancelled in spite of appearing the SEE.

The Student, in each subject, shall have to earn 35% of marks (i.e. 14 marks out of 40 marks) in
CIE, 35% of marks (i.e. 21 marks out of 60) in SEE and overall 40% of marks (i.e. 40 marks out
of 100 marks)both CIE and SEE marks put together.
Cycle 1:
Week - 1:
1. (i) Use a web browser to go to the Python website http://python.org. This page
contains information about Python and links to Python-related pages, and it gives you
the ability to search the Python documentation.
(ii) Start the Python interpreter and type help() to start the online help utility.

def addition(num1,num2):
return num1 + num2
def subtraction(num1,num2):
return num1 - num2
def multiplication(num1,num2):
return num1 * num2
def division(num1,num2):
return num1 // num2
def remainder(num1,num2):
return num1 % num2

print(“select the ptions\n1.addition\n2.subtraction\n3.multiplication\n4.division\n


5.remainder")
operation=int(input("enter the choice"))
num1=int(input("enter num1:"))
num2=int(input("enter num2:"))
if operation==1:
print("sum is",addition(num1,num2))
elif operation==2:
print("subtraction is",subtraction(num1,num2))
elif operation==3:
print("mulitplicationis",multiplication(num1,num2))
elif operation==4:
print("division is", division(num1,num2))
elif operation==5:
print("remainder is", remainder(num1,num2) )
else:
print("invalid input")

(iii)Write a program to calculate compound interest when principal, rate and number of
periods are given.
principalAmount = float(input())
rateOfInterest = float(input())
timePeriod = float(input())
CI = principalAmount*(1 + rateOfInterest)**timePeriod # annually compounded
print(CI)
(iv)Given coordinates (x1, y1), (x2, y2) find the distance between two points.
x1,y1,x2,y2 = input().split()
distance = ((int(x1) - int(x2))**2 + (int(y2) - int(y1))**2) ** 0.5
print("%.2f"%distance)

2. Read name, address, email and phone number of a person through keyboard
and print the details.
name=input("enter name:")
address=input("enter address:")
email=input("enter email:")
phonenumber=int(input("enter phone number:"))
print(name)
print(address)
print(email)
print(phonenumber)

Week - 2:
1. Find the Euclidean distance with the given values and check the validity of values to
find the distance.
from scipy.spatial import distance
x1,y1,x2,y2 = input().split()
distance = distance.euclidean((int(x1),int(y1)),(int(x2),int(y2)))
print(distance)

2. Generate a random number between 1-10 and ask the user to guess the number.
Give chance for 3 times. If guessed correctly then congratulate otherwise print
message as sorry.
import random
secretNum = random.randint(1,10)
print(secretNum)
for chance in range(3) :
num = int(input("ENTER A NUMBER BTW 1 TO 10 : "))
if chnce == 2 and num != secretNum :
print("SORRY")
elif num >secretNum :
print("ENTERED NUMBER IS GREATER THAN SECRET NUMBER")
elif num <secretNum :
print("THE ENTERED NUMBER IS LESS THAN THE SECRET NUMBER")
else :
print("CONGRATULATIONS....")
break
3. Accept a string and generate the combinations of string until the source string
doesn’t repeated.
from itertools import permutations
word = input("Enter a string : ")
per = permutations(list(word))
for words in per :
if words != tuple(word):
print("".join(words),end = " ")

4. Generate prime numbers of Fibonacci series between 1-50.


def isPrime(num) :
count = 0
for divisor in range(1,num + 1) :
if num % divisor == 0 :
count +=1
if count == 2 :
return True
else :
return False
def fibPrime(range) :
term1 = 0
term2 = 1
nextTerm = term1 + term2
while nextTerm<= range :
if isPrime(nextTerm) == True :
print(nextTerm)
term1,term2 = term2,nextTerm
nextTerm = term1 + term2
fibPrime(50)

Week - 3:
1. (i) Write a program to convert a list and tuple into arrays.
import numpy as np
numList = [int(num) for num in input().split()]
array1 = np.asarray(numList)
print(array1)
num_tup=[int(num) for num in input().split()]
print(np.asarray(num_tup))
(ii) Write a program to find common values between two arrays.
import numpy as np
nums1 = [int(num) for num in input().split()]
nums2 = [int(num) for num in input().split()]
arr1 = np.array(nums1)
arr2 = np.array(nums2)
print(np.intersect1d(arr1,arr2))

2. Write a program to add comma separators in a given big number as per the
standard American convention. Ex: i/p: 100000000 o/p: 100,000,000.
num = int(input())
numList = [num for num in str(num)]
count = 0
for index in range(len(numList) - 1,0,-1) :
count += 1
if count == 3 :
numList.insert(index,",")
count = 0
for num in numList :
print(num,end = "")

3. Write a program to convert given formula 3X+4Y as 3*X+4*Y and 3(X+Y) as


3*X+3*Y etc.

import re
def convert_formula(formula):
formula = re.sub(r'(\d)(X|Y)', r'\1*\2', formula)
def distribute(match):
number = match.group(1)
x_term = match.group(2)
y_term = match.group(3)
if y_term:
return f"{number}*{x_term} + {number}*{y_term}"
else:
return f"{number}*{x_term}"
formula = re.sub(r'(\d+)\((X)\+?(Y)?\)', distribute, formula)
return formula
formula1 = "3X+4Y"
formula2 = "3(X+Y)"
a = convert_formula(formula1)
b = convert_formula(formula2)
print(a)
print(b)
Week - 4:
1. Write a function called is_sorted that takes a list as a parameter and returns True if
the list is sorted in ascending order and False otherwise.
def is_sorted(lst):
for i in range (len(lst)-1):
if lst[i]>lst[i+1]:
return False
return True
lst=[int(num) for num in input().split()]
res=is_sorted(lst)
print(res)

2. Write a function called has_duplicates that takes a list and returns True if there is
any element that appears more than once. It should not modify the original list.
def has_duplicates(lst):
seen=set()
for i in lst:
if i in seen:
return True
seen.add(i)
return False
lst=[int(num) for num in input().split()]
res=has_duplicates(lst)
print(res)

3. (i)Write a function called remove_duplicates that takes a list and


returns a new list with only The unique elements from the original.
Hint: they don’t have to be in the same order.
def remove(lst):
seen = set()
ans = []
for item in lst:
if item not in seen:
seen.add(item)
ans.append(item)
return ans
lst=[int(num) for num in input().split()]
res=remove(lst)
print(res)
3. (ii) The wordlist I provided, words.txt, doesn’t contain single letter words.
So
you might want to add “I”, “a”, and the empty string.
def update_wordlist(filename):
with open(filename, 'r') as file:
words = file.read().splitlines()
additional_words = ["i", "a", ""]
for word in additional_words:
if word not in words:
words.append(word)
with open(filename, 'w') as file:
for word in words:
file.write(f"{word}\n")
update_wordlist('word.txt')
3. (iii)Write a python code to read dictionary values from the user Construct a
function to invert its content i.e., keys should be values and values should
bekeys.
def invertDict(user_dict) :
new_dict = dict()
for key,value in user_dict.items() :
new_dict[value] = key
return new_dict
user_dict = dict()
num_entries = int(input("Enter the number of entries you want to add: "))
for keyValues in range(num_entries):
key = input("Enter key: ")
value = input("Enter value: ")
user_dict[key] = value

print("Original dictionary : \t",user_dict)


print("Inverted dictionary : \t",invertDict(user_dict))
4.(i) Add a comma between the characters. If the given word Is 'Apple', it
should become 'A,p,p,l,e'.
def add_commas(word):
return ",".join(word[:len(word)])
word = input()
print(add_commas(word))
4.(ii) Remove the given word in all the places in a string
def remove_word(sentence, word):
return sentence.replace(word, '')
sentence = input("Enter a sentence: ")
word = input("Enter the word to remove: ")
modified_sentence = remove_word(sentence, word)
print("Modified sentence:", modified_sentence)
4.(iii) Write a function that takes a sentence as an input parameter and
replaces the first letter of every word with the corresponding upper case letter
and the rest of the In the word by corresponding letters in lower case without
using a built-in function
def up(sen):
s=""
for i in sen.split(" "):
s += i[0].upper()+i[1:]+" "
return s
sen = input()
print(up(sen))

5.Writea recursive function that generates all binary strings of n-bit length.
def generate_binary_strings(n):
if n == 1:
return ['0', '1']
else:
prev_strings = generate_binary_strings(n - 1)
new_strings = []
for string in prev_strings:
new_strings.append(string + '0')
new_strings.append(string + '1')
return new_strings
n = int(input("Enter the number of bits (n): "))
binary_strings = generate_binary_strings(n)
print(f"All binary strings of {n}-bit length:")
for binary_string in binary_strings:
print(binary_string)

Week - 5:
1.(i)Write a python program that defines a matrix and prints.
# Creation of matrix
def matrix(rows : int, cols :int) :
matA = []
for index1 in range(0,rows) :
row = []
for index2 in range(0,cols) :
row.append(int(input()))
matA.append(row)
return matA
# Printing matrix
def printMatrix(mat : list[list[int]]) -> None :
for row in range(len(mat)) :
for col in range(len(mat[0])) :
print(mat[row][col],end = " ")
print()
mat = matrix(3,3)
printMatrix(mat)

1.(ii) Write a python program to perform addition of two square matrices


def addition(matA : list[list[int]], matB : list[list[int]]) -> list[list[int]] :
matC = []
for row in range(len(matA)) :
rows = []
for col in range(len(matA[0])) :
rows.append(matA[row][col] + matB[row][col])
matC.append(rows)
return matC
# Creation of matrix
def matrix(rows : int, cols :int) :
matA = []
for index1 in range(0,rows) :
row = []
for index2 in range(0,cols) :
row.append(int(input()))
matA.append(row)
return matA
# Printing matrix
def printMatrix(mat : list[list[int]]) -> None :
for row in range(len(mat)) :
for col in range(len(mat[0])) :
print(mat[row][col],end = " ")
print()
mat = matrix(3,3)
printMatrix(mat)
print("Matrix 1 \t")
matA = matrix(2,2)
print("Matrix 2 \t")
matB = matrix(2,2)
matC = addition(matA,matB)
printMatrix(matC)
1.(iii) Write a python program to perform multiplication of two square
matrices.
def mul_matrices(matA,matB) :
matC = [[0,0,0],[0,0,0],[0,0,0]]
for x in range(len(matA)) :
for y in range(len(matB[0])):
for k in range(len(matB)):
matC[x][y] += matA[x][k] * matB[k][y]
print("Resultant matrix: ")
for a in matC:
print(a)

2. How do you make a module? Give an example of construction of a module


using Different geometrical shapes and operations on them as its functions.
import math
def square_area(side_length):
return side_length ** 2
def rectangle_area(length, width):
return length * width
def circle_area(radius):
return math.pi * radius ** 2
def rectangle_perimeter(length, width):
return 2 * (length + width)
def circle_circumference(radius):
return 2 * math.pi * radius
def cube_volume(side_length):
return side_length ** 3

3.Use the structure of exception handling all general purpose exceptions.


num1 = input()
num2 = input()
try :
div = int(num1) / int(num2)
print(div)
except ZeroDivisionError :
print("ZERO DIVISION ERROR")
except ValueError :
print("TYPE IS MISMATCHED!")
finally :
print("THE BLOCK HAS SUCCESSFULLY EXECUTED")
Cycle2:
Week- 6:
(i)Write a function called draw_rectangle that takes a Canvas and a
Rectangle as arguments and draws a representation of the Rectangle on the
Canvas.
import tkinter as tk
class Rectangle:
def __init__(self,x1,y1,x2,y2):
self.x1=x1
self.y1=y1
self.x2=x2
self.y2=y2
def draw_rectangle(canvas,rectangle):
canvas.create_rectangle(rectangle.x1,rectangle.y1,rectangle.x2,rectangle.y2,
outline="black",fill="green")
root=tk.Tk()
root.title("draw rectangle")
canvas=tk.Canvas(root,width='500',height='500')
canvas.pack()
rect=Rectangle(50,50,200,200)
draw_rectangle(canvas,rect)
root.mainloop()
1.(ii)Add an attribute named color to your Rectangle objects and modify
draw_rectangle so that it uses the color attribute as the fill color.
import tkinter as tk
class Rectangle:
def __init__(self, x1, y1, x2, y2, color="blue"):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.color = color
def draw_rectangle(canvas, rectangle):
canvas.create_rectangle(rectangle.x1, rectangle.y1, rectangle.x2,
rectangle.y2, outline="black", fill=rectangle.color)
root = tk.Tk()
root.title("Draw Rectangle")
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
rect = Rectangle(50, 50, 150, 150, color="blue")
draw_rectangle(canvas, rect)
root.mainloop()
1.(iii) Write a function called draw_point that takes a Canvas and a Point as
arguments and draws a representation of the Point on the Canvas
import tkinter as tk
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def draw_point(canvas, point, radius=3):
x1, y1 = point.x – radius, point.y – radius
x2, y2 = point.x + radius, point.y + radius
canvas.create_oval(x1, y1, x2, y2, outline=”black”, fill=”black”)
root = tk.Tk()
root.title(“Draw Point”)
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
point = Point(200, 200)
draw_point(canvas, point)
root.mainloop()
1.(iv)Define a new class called Circle with appropriate attributes and
instantiate a few Circle objects. Write a function called draw_circle that
draws circles on the canvas.
Import tkinter as tk
class Circle:
def __init__(self, x, y, radius):
self.x = x
self.y = y
self.radius = radius
def draw_circle(canvas, circle):
x1, y1 = circle.x – circle.radius, circle.y – circle.radius
x2, y2 = circle.x + circle.radius, circle.y + circle.radius
canvas.create_oval(x1, y1, x2, y2, outline=”black”, fill=”green”)
def draw_circles(canvas, circles):
for circle in circles:
draw_circle(canvas, circle)
root = tk.Tk()
root.title(“Draw Circles”)
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
circles = [
Circle(100, 100, 30),
Circle(200, 200, 40),
Circle(300, 300, 50)
]
draw_circles(canvas, circles)
root.mainloop()
3. Write a Python program to demonstrate the usage of Method
Resolution Order (MRO) in multiple levels of Inheritances.
Class A:
def method(self):
print(“method in A”)
class B(A):
def method(self):
print(“method in B”)
super().method()
class C(A):
def method(self):
print(“method in C”)
super().method()
class D(B,C):
def method(self):
print(“method in D”)
super().method()
d=D()
d.method()
print(“MRO in D: “,D.mro())
3.Write a python code to read a phone number and email-idfrom the user and
validate it for correctness.
Import re
def validate_phone_number(phone_number):
pattern = r’^\d{10}$’
if re.match(pattern, phone_number):
return True
else:
return False
def validate_email(email):
pattern = r’^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$’
if re.match(pattern, email):
return True
else:
return False
phone_number = input(“Enter your phone number: “)
print(f”Phone number entered: {phone_number}”)
if validate_phone_number(phone_number):
print(“Phone number is valid.”)
else:
print(“Phone number is invalid.”)
email = input(“Enter your email address: “)
print(f”Email address entered: {email}”)
if validate_email(email):
print(“Email address is valid.”)
else:
print(“Email address is invalid.”)

Week- 7:
1.Write a Python code to merge two given file contents into a third file.
with open("file1","w") as fp1 :
data = "Hello World"
fp1.write(data)

with open("file2","w") as fp2 :


data = "Vaishnavi"
fp2.write(data)

with open("file1","r") as fp1 :


print(fp1.read())

with open("file2","r") as fp2 :


print(fp2.read())
2.Write a Python code to open a given file and construct a Function to check
for given words present in it and display on found.
def checkWordInFile(file,word : str) -> bool :
try :
with open(file,"r") as file1 :
data = file1.read()
if word in data :
return True
return False

except FileNotFoundError :
print("File not found")

with open("file1","w") as fp1 :


data = "There is a girl named Vaishnavi"
fp1.write(data)

if checkWordInFile("file1","Vaishnavi") :
print("word found")
else :
print("word not found")
3.Write a Python code to Read text from a text file, find the word with most
number of occurrences.
def mostOccurences(file):
try :
with open(file,"r") as fp1 :
data = fp1.read()
occurences = dict()
for word in data.split() :
if word not in occurences :
occurences[word] = 1
else :
occurences[word] += 1
key = max(occurences, key= lambda value: occurences[value])
print(occurences)
return key

except FileNotFoundError :
print("File not found")

with open("file1","w") as fp1 :


data = "I felt happy because I saw the others were happy and because I knew I should feel happy but I
wasn't really happy"
fp1.write(data)

mostOccurences("file1")

4.Write a function that reads a file file1 and displays the number of words,
number of vowels, blank spaces, lower case letters and uppercase letters
def analyzeFile(file) -> list[int] :
try :
with open(file,"r") as fp1 :
data = fp1.read()
noOfWords = len(data.split())
noOfVowels = len([char for char in data if char in "aeiou"])
blankSpaces = data.count(" ")
lowerCaseLetters = len([char for char in data if char.islower()])
upperCaseLetters = len([char for char in data if char.isupper()])
return [noOfWords, noOfVowels, blankSpaces,lowerCaseLetters,upperCaseLetters]

except FileNotFoundError:
print("File not Found")

with open("file1","w") as fp1 :


data = "This is Vaishnavi Cse A Student"
fp1.write(data)

print(analyzeFile("file1"))
WEEK – 8:
1.Import Numpy, Plotpy and Scipy and explore their functionalities.
import numpy as np
import plotly.graph_objects as go
from scipy import stats
# Numpy
array = np.array([1, 2, 3])
print("Numpy array:", array)

# Plotly
fig = go.Figure(data=go.Scatter(x=[1, 2, 3], y=[1, 4, 9], mode='markers'))
fig.show()

# Scipy
data = [1, 2, 3, 4, 5]
mean = stats.tmean(data)
print("Mean of data using Scipy:", mean)

2. Install Numpy package with pip and explore it.


pip install numpy
import numpy as np
array = np.array([1, 2, 3])
print("Numpy array:", array)
print("Array mean:", np.mean(array))

3.Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-
OR.
def AND(a, b):
return a and b
def OR(a, b):
return a or b
def NOT(a):
return not a
def XOR(a, b):
return a ^ b
# Example inputs
num1 = int(input("Enter first binary input (0 or 1): "))
num2 = int(input("Enter second binary input (0 or 1): "))
# Validate inputs
if num1 not in (0, 1) or num2 not in (0, 1):
print("Invalid input. Please enter 0 or 1.")
else:
# AND gate
print(f"AND({num1}, {num2}) = {AND(num1,num2)}")
# OR gate
print(f"OR({num1}, {num2}) = {OR(num1,num2)}")
# NOT gate (applied only to the first input for demonstration)
print(f"NOT({num1}) = {int(NOT(num1))}")
# XOR gate
print(f"XOR({num1}, {num2}) = {XOR(num1,num2)}")

4. Write a program to implement Half Adder, Full Adder,and Parallel Adder.


def half_adder(a, b):
sum_ = a ^ b
carry = a & b
return sum_, carry
def full_adder(a, b, c):
sum1, carry1 = half_adder(a, b)
sum2, carry2 = half_adder(sum1, c)
carry_out = carry1 | carry2
return sum2, carry_out
a, b, c = 1, 0, 1
sum_, carry = full_adder(a, b, c)
print(f"Full adder result: Sum = {sum_}, Carry = {carry}")

5.Write a GUI program to create a window wizard having two text labels, two
text fields and two buttons as Submit and Reset.
from tkinter import Tk, Label, Entry, Button
def submit():
print("Submitted")
def reset():
entry1.delete(0, 'end')
entry2.delete(0, 'end')
root = Tk()
root.title("Window Wizard")
label1 = Label(root, text="Label 1")
label1.pack()
entry1 = Entry(root)
entry1.pack()
label2 = Label(root, text="Label 2")
label2.pack()
entry2 = Entry(root)
entry2.pack()
submit_button = Button(root, text="Submit", command=submit)
submit_button.pack()
reset_button = Button(root, text="Reset", command=reset)
reset_button.pack()
root.mainloop()
Viva Questions

Q1: Name the key features of Python?


Answer: There are many key features in python and some of them are listed below:
Dynamically-typed
Interpreted
Object-oriented
Concise and simple

Q2: How to check if all characters in a string are alphanumeric?


Answer: isalnum(): In python, we can use the "isalnum()" method to check whether all the
characters are alphanumeric or not in a string variable.

Q3: Name the built-in types available in Python?


Answer: We have Mutable and Immutable as built-in types in python, listed as below:
a) The mutable ones include:
List
Sets
Dictionaries
b) The immutable types include:
Strings
Tuples
Numbers

Q4: Explain the difference between a list and a tuple?


Answer: The list is mutable while the tuple is not. Tuples can be hashed as in the case of making
keys for dictionaries.

Q5: What is the use of %s in python?


Answer: "%s" is a format specifier which transmutes any value into a string.

Q6: What is a pass in Python?


Answer: No-operation Python statement refers to pass.

Q7: How are files deleted in Python?


Answer: To delete a file in Python:
Import OS module
Use os.remove() function

Q8: What is pep 8?


Answer: Python Enhancement Proposal or pep 8 is a set of rules that specify how to format
Python code for maximum readability.

Q9: What is [::-1} used for?


Answer: [::-1} reverses the order of an array or a sequence. However, the original array or the
list remains unchanged.
Q10: What is Numpy?
Answer: NumPy stands for "Numerical Python".
It is used for efficient and general numeric computations on numerical data saved in arrays. E.g.,
sorting, indexing, reshaping, and more.

Q11: What is Scipy?


Answer: SciPy stands for "Scientific Python".
This module is a collection of tools in Python used to perform operations such as integration,
differentiation, and more.

Q12: Explain how to delete a file in Python?


Answer: Using a command os.remove(file name / file path) or os.unlink(file name / file path).

Q13: How can you access a module written in Python from C?


Answer: If we need to access the logic from a module written in the programming C we can use
the "PyImport_ImportModule" function with a parameter name as the module name like below:
Module = =PyImport_ImportModule("<modulename>");

Q14: What is slicing?


Answer: Slicing is a technique that allows us to retrieve only a part of a list, tuple, or string.

Q15: How do you reverse a list?


Answer: We have a list of built-in functions available with the "List" collection and from them
using the reverse() method we can reverse the list.

Q16. What type of language is python? Programming or scripting?


Ans: Python is capable of scripting, but in general sense, it is considered as a general-purpose
programming language.

Q17.Python an interpreted language. Explain.


Ans: An interpreted language is any programming language which is not in machine-level code
before runtime. Therefore, Python is an interpreted language.

Q18.What is pep 8?
Ans: PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format
Python code for maximum readability.

Q19.What are the benefits of using Python?


Ans: The benefits of using python are-
Easy to use– Python is a high-level programming language that is easy to use, read, write and
learn.
Interpreted language– Since python is interpreted language, it executes the code line by line and
stops if an error occurs in any line.
Dynamically typed– the developer does not assign data types to variables at the time of coding. It
automatically gets assigned during execution.
Free and open-source– Python is free to use and distribute. It is open source.
Extensive support for libraries– Python has vast libraries that contain almost any function
needed. It also further provides the facility to import other packages using Python Package
Manager(pip).
Portable– Python programs can run on any platform without requiring any change.

Q20. What does [::-1} do?


Ans: [::-1] is used to reverse the order of an array or a sequence.

Q21. What are python iterators?


Ans: Iterators are objects which can be traversed though or iterated upon.

Q22. What is the difference between range & xrange?


Ans:For the most part, xrange and range are the exact same in terms of functionality. They both
provide a way to generate a list of integers for you to use, however you please. The only
difference is that range returns a Python list object and x range returns an xrange object.
This means that xrange doesn’t actually generate a static list at run-time like range does. It
creates the values as you need them with a special technique called yielding. This technique is
used with a type of object known as generators. That means that if you have a really gigantic
range you’d like to generate a list for, say one billion, xrange is the function to use.
This is especially true if you have a really memory sensitive system such as a cell phone that you
are working with, as range will use as much memory as it can to create your array of integers,
which can result in a Memory Error and crash your program. It’s a memory hungry beast.

Q23. How do you write comments in python?


Ans: Comments in Python start with a # character. However, alternatively at times, commenting
is done using docstrings(strings enclosed within triple quotes).

Q24. What is pickling and unpickling?


Ans:Pickle module accepts any Python object and converts it into a string representation and
dumps it into a file by using dump function, this process is called pickling. While the process of
retrieving original Python objects from the stored string representation is called unpickling.

Q25. What are the generators in python?


Ans: Functions that return an iterable set of items are called generators.

Q26. How will you capitalize the first letter of string?


Ans: In Python, the capitalize() method capitalizes the first letter of a string. If the string already
consists of a capital letter at the beginning, then, it returns the original string.

Q27. How will you convert a string to all lowercase?


Ans: To convert a string to lowercase, lower() function can be used.
Q28. How to comment multiple lines in python?
Ans: Multi-line comments appear in more than one line. All the lines to be commented are to be
prefixed by a #. You can also a very good shortcut method to comment multiple lines. All you
need to do is hold the ctrl key and left click in every place wherever you want to include a #
character and type a # just once. This will comment all the lines where you introduced your
cursor.

Q29.What are docstrings in Python?


Ans: Docstrings are not actually comments, but, they are documentation strings. These
docstrings are within triple quotes. They are not assigned to any variable and therefore, at times,
serve the purpose of comments as well.

Q30.What are Python namespaces?


Ans: A namespace in python refers to the name which is assigned to each object in python. The
objects are variables and functions. As each object is created, its name along with space(the
address of the outer function in which the object is), gets created. The namespaces are
maintained in python like a dictionary where the key is the namespace and value is the address of
the object. There 4 types of namespace in python-
Built-in namespace– These namespaces contain all the built-in objects in python and are
available whenever python is running.
Global namespace– These are namespaces for all the objects created at the level of the main
program.
Enclosing namespaces– These namespaces are at the higher level or outer function.
Local namespaces– These namespaces are at the local or inner function.

You might also like