Python Lab Manual (AVN)-1
Python Lab Manual (AVN)-1
0 1 2 2
Course Objectives:
Course Outcomes: After completion of the course, the student should be able to
Week -1&2:
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.
3.
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
4. Read name, address, email and phone number of a person through keyboard and print the details.
Week – 3&4:
1. Print the below triangle using for loop.
5
44
333
2222
11111
2. Write a program to check whether the given input is digit or lowercase character or
upper case character or a special character (use 'if-else-if' ladder)
3. Python Program to Print the Fibonacci sequence using while loop
4. Python program to print all prime numbers in a given interval (use break)
Week – 5&6:
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 function called gcd that takes parameters a and b and returns their greatest common
divisor.
3. Write a function called palindrome that takes a string argument and returns True if it is a
Palindrome and False otherwise. Remember that you can use the built-in function len to check the
length of a string.
Week – 7&8:
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.
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.
3. 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?
4. Writes a recursive function that generates all binary strings of n-bit length
Week – 9&10:
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.
Week-11&12:
1. a. 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.
b. Add an attribute named color to your Rectangle objects and modify draw_rectangle so
that it uses the color attribute as the fill color.
c. Write a function called draw_point that takes a Canvas and a Point as arguments and draws
arepresentation of the Point on the Canvas.
d. 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
multiplelevels of Inheritances.
3. Write a python code to read a phone number and email-id from the user and validate it
forcorrectness.
Week- 13&14:
1. Write a Python code to merge two given file contents into a third file.
2. Write a Python code to open a given file and construct a function to check for given words
present init 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 – 15&16:
1. Import numpy, Plotpy and Scipy and explore their functionalities.
2. a) 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
buttonsas Submit and Reset
TEXT BOOKS:
1. Supercharged Python: Take your code to the next level, Overland
2. Learning Python, Mark Lutz, O'reilly
REFERENCE BOOKS:
1. Python Programming: A Modern Approach, Vamsi Kurama, Pearson
2. Python Programming A Modular Approach with Graphics, Database, Mobile, and Web
Applications, Sheetal Taneja, Naveen Kumar, Pearson
3. Programming with Python, A User’s Book, Michael Dawson, Cengage Learning, India
Edition
4. Think Python, Allen Downey, Green Tea Press
5. Core Python Programming, W. Chun, Pearson
6. Introduction to Python, Kenneth A. Lambert, Cengage
WEEK-1&2:
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.
Output:
import webbrowser
open('http://www.python.or
g')
help()
Output:
Welcome to Python 3.7's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the internet at https://docs.python.org/3.7/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
Calculator. CODE:
first = input("Enter first number : ")
second = input("Enter second number :
")first = int(first)
second = int(second)
print("----press keys for operator (+,-,*,/,%)--------- ")
operator = input("Enter operator :
") if operator == "+":
print(first + second)
elif operator == "-":
print(first -
second)
elif operator == "*":
print(first * second)
elif operator == "/":
print(first /
second)
elif operator == "%":
print(first %
second)
else:
print("Invalid Operation")
OUT PUT:
Enter first number : 4
Enter second number : 5
----press keys for operator (+,-,*,/,%)
Enter operator : *
20
3. (i) Write a program to calculate compound interest when principal, rate and
numbers o f p e ri od s a re given.
3. (ii)Given coordinates (x1, y1), (x2, y2) find the distance between
twopoints.
x1=int(input("enter x1 :
")) x2=int(input("enter x2
: ")) y1=int(input("enter
y1 : "))
y2=int(input("enter y2 :
"))
out put:
enter x1 : 5
enter x2 : 8
enter y1 : 7
enter y2 : 5
distance between (5, 8) and (7, 5) is : 3.605551275463989
4. Read name, address, email and phone number of a person through keyboard
and print the details.
print("Enter your name: ")
name = input()
print("Enter your phone number: ")
ph_num = input()
print("Enter your email: ")
email = input()
print("Enter your address: ")
address = input()
Details:
Name:
Address:
Email:
Phone Number:
WEEK-3&4:
1. Print the below triangle using for loop.5
44
333
2222
11111
for i in range(4,0,-1):
for j in range(i,6):
print(i, end=””)
print(i)
Output:
44
333
2222
11111
print("The Given Character ", ch, "is Not a Lower or Uppercase Alphabet")
Output:
if terms <= 0:
print("Please enter a positive integer")
elif terms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,n2)
while count < terms-2:
nth = n1 + n2
print(nth)
n1=n2
n2 = nth
count += 1
Output:
How many terms? 9
Fibonacci sequence:
0 1 1 2 3 5 8 13 21
4. Python program to print all prime numbers in a given interval (use break).
lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) ==0:
break
else:
print(num)
Output:
print("List after
conversion to array : " +
str(res))
x = (6,4,8,9,10)
y = list(x)
print(y)
z = ((6,4,8), (9,10))
y = [a for b in z for a in
b]
print(y)
Output:
[2, 8, 4, 10, 5]
<class 'list'>
(11, 21, 19, 18, 46, 29)
<class 'tuple'>
converting Python list, tuple to array
by using np.asarray() function
[ 2 8 4 10 5]
[11 21 19 18 46 29]
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
a=[1,2,3,4]
b=[4,5,6,7]
print(set(a).intersection(set(b)))
Output:
<class 'numpy.ndarray'>
Common values between two arrays: [4]
2. Write a function called gcd that takes parameters a and b and returns their
greatest common divisor.
if x > y:
small = y
else:
small = x
for i in range(1, small + 1):
if((x % i == 0) and (y %
i == 0)):gcd = i
return gcd
a = 60
b = 48
3. Write a function called palindrome that takes a string argument and returns true if it is
a palindrome and false otherwise. Remember that you can use the built-in function len to
check the length of a string.
string=input(("Enter a letter:"))
if(string==string[::-1]):
Source code:
def is_sorted(lst):
return all(lst[i] <= lst[i+1] for i in range(len(lst)-1))
print(is_sorted([5,4,3,2,1]))
Output:
before sort list is: [5,4,3,2,1]
after sort list is: [1, 2,3,4,5]
True
2. (i) 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.
Source code:
def has_duplicates(lst):
unique_elements = set(lst)
return len(unique_elements) < len(lst)
print(has_duplicates([1, 2, 3, 4, 5]))
print(has_duplicates([1, 2, 3, 4, 4, 5]))
[if the list has duplicates it will give output as True, else it will give False]
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_duplicates(lst):
unique_elements = set(lst)
unique_lst = list(unique_elements)
return unique_lst
lst = [1, 2, 3, 4, 4, 5]
unique_lst = remove_duplicates(lst)
print(unique_lst)
Output:
True
True
List is empty.
List contains only one element.
False
2.(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.
Source code:
with open("words.txt", "a") as f:
f.write("\nI\na\n")
f.write("\n")
[*file operation kind of program*]
Output:
2.(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.
def invert_dict(d):
inverted = {}
for key in d:
value = d[key]
if value not in inverted:
inverted[value] = [key]
else:
inverted[value].append(key)
return inverted
d = {}
3. i) Add a comma between the characters. If the given word is ‘Apple’, it should
become ‘A,p,p,l,e’
Source code:
word = input("Enter a word: ")
comma_word = ",".join(word)
print(comma_word)
Output:
Enter a word:APPLE
A,P,P,L,E
Source code:
def remove_word(string, word):
new_string = string.replace(word, "")
return new_string
string = input("Enter a string: ")
word = input("Enter a word to remove: ")
new_string = remove_word(string, word)
print("New string:", new_string)
Output:
Enter a string:avniet aiml
avnietaiml
iii) Write a function that takes a sentence as an input parameter and replaces the
first letter of every word with corresponding upper case letter and the rest of the
letters in the word by corresponding letters in lower case without using an in-built
function?
Source code:
def capitalize_words(sentence):
words = sentence.split()
new_sentence = ""
for word in words:
new_word = word[0].upper() + word[1:].lower()
new_sentence += new_word + " "
return new_sentence.strip()
sentence= input("Enter a sentence: ")
new_sentence = capitalize_words(sentence)
print(new_sentence)
Output:
sentence = "hello cSE and aI&ML STUDENTS, how are you."
print(capitalize_first_letter(sentence))
OUT PUT: Hello Cse And Ai&ml Students, How Are You.
4. Write a recursive function that generates all binary strings of n-bit length.
Source code:
def generate_binary_strings(n):
if n == 0:
return ['']
else:
strings = generate_binary_strings(n - 1)
return [s + '0' for s in strings] + [s + '1' for s in strings]
strings = generate_binary_strings(3)
print(strings)
Output:
00
01
10
11
Week-9&10:
1. i) Write a python program that defines a matrix and prints
Source code:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print(row)
Output:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Source code:
#defining the matrices
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
#declaring the resultant matrix
result_matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
#modifying the resultant matrix to the sum
for i in range(3):
for j in range(3):
result_matrix[i][j] = matrix1[i][j] + matrix2[i][j]
#printing the resultant matrix
for row in result_matrix:
print(row)
Output:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Source code:
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
def circle_area(radius):
return math.pi * radius ** 2
def circle_perimeter(radius):
return 2 * math.pi * radius
print(geometry.circle_area(5))
print(geometry.rectangle_perimeter(4, 6))
print(geometry.triangle_area(3, 4))
Output:
78.53981633974483
20
6.0
3. Use the Structure of Exception hadling all general purpose exceptions using
python
Source code:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("The result is:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
except Exception as e:
print("An error occurred:", e)
Output:
Enter a number:10
Enter another number:5
The result is:2
WEEK-11&12:
1. (a)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 using python
import turtle
1.(b) add an a attribute named color to your rectangle objects and modify draw
rectangle so that it uses the color attribute as athe fill color
import turtle
col = input("Enter the color name or hex value of color(# RRGGBB): ")
Output:
1.(c) Write a function called draw point that takes a canvas and a point as arguments and
draw a representation of the point on the canvas
import tkinter as tk
# define a point
point = (200, 200)
Output:
1.(d) Define a new class called circle with appropriate attributes and instantiate a few circle
objects . Write a function called draw circles that draw circles on the canvas
Source code:
import turtle
class Circle:
t.goto(circle.x, circle.y)
t.pendown()
t.circle(circle.radius)
t.penup()
turtle.done()
# Create some Circle objects
c1 = Circle(0, 0, 50)
c2 = Circle(-100, 100, 75)
Output:
2.Write a Python program to demonstrate the usage of method resolution order (MRO) in
multiple levels of inheritance
Source code:
class A:
def method(self):
print("A's method called")
class B(A):
def method(self):
print("B's method called")
super().method()
class C(A):
def method(self):
print("C's method called")
super().method()
super().method()
d = D()
d.method()
Python follows a depth-first lookup order and hence ends up calling the method from class A.
By following the method resolution order, the lookup order as follows.
Class D -> Class B -> Class C -> Class A
3.Write a Python code to read phone number and email id from the user and validate it
for correctness
Source code:
import re
WEEK-13&14:
1. Write a program to merge two given files contents into the third file
Source code:
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
Source code:
# Example usage
file_path = 'example.txt'
words_to_check = ['hello', 'world', 'Python']
check_words_in_file(file_path, words_to_check)
Output:
ENTER THE WORD TO SEARCH===world
word found
3. Write a python code read text from the text file, find the word with most number of
occurrences from collections import Counter
Source code:
# Open the file and read its contents
with open('filename.txt', 'r') as file:
contents = file.read()
4. write a function that reads a file file1 and display the number of words, number of
vowels, blank spaces, lower case and upper case letters
Source code:
def analyze_file(file_name):
with open(file_name, 'r') as f:
text = f.read()
num_words = len(text.split())
num_vowels = sum(1 for char in text if char.lower() in 'aeiou')
num_spaces = sum(1 for char in text if char == ' ')
num_lower = sum(1 for char in text if char.islower())
num_upper = sum(1 for char in text if char.isupper())
Plotly:
Plotly is a Python library that provides a variety of graphing tools, such as scatter
plots, line plots, bar charts, histograms, heatmaps, and more. Plotly provides a user-
friendly interface for creating interactive plots and visualizations that can be easily
shared online or embedded into web pages.
SciPy :
SciPy (Scientific Python) is a Python library for scientific computing and
technical computing. It provides a wide range of scientific algorithms and
functions that can be used for tasks such as optimization, integration,
interpolation, signal processing, linear algebra, and more. SciPy builds on top of
the NumPy library, which provides support for large, multi-dimensional arrays
and matrices.
2. Write a program to implement digital logic gates- AND, OR, NOT, EX-OR
Source code:
def AND_gate(x1, x2):
Implements the AND logic gate.
Inputs:
x1 (int): The first input to the AND gate (either 0 or 1).
x2 (int): The second input to the AND gate (either 0 or 1).
Returns:
int: The output of the AND gate (either 0 or 1).
if x1 == 1 and x2 == 1:
return 1
else:
return 0
Inputs:
x1 (int): The first input to the OR gate (either 0 or 1).
x2 (int): The second input to the OR gate (either 0 or 1).
Returns:
int: The output of the OR gate (either 0 or 1).
if x1 == 1 or x2 == 1:
return 1
else:
return 0
def NOT_gate(x):
Inputs:
x (int): The input to the NOT gate (either 0 or 1).
Returns:
int: The output of the NOT gate (either 0 or 1).
if x == 1:
return 0
else:
return 1
Returns:
int: The output of the XOR gate (either 0 or 1).
if x1 == x2:
return 0
else:
return 1
print("OR gate")
print(OR_gate(0, 0)) # Output: 0
print(OR_gate(0, 1)) # Output: 1
print(OR_gate(1, 0)) # Output: 1
print(OR_gate(1, 1)) # Output: 1
print("NOT gate")
print(NOT_gate(0)) # Output: 1
print(NOT_gate(1)) # Output: 0
print("XOR gate")
print(XOR_gate(0, 0)) # Output: 0
print(XOR_gate(0, 1)) # Output: 1
print(XOR_gate(1, 0)) # Output: 1
print(XOR_gate(1, 1)) # Output: 0
Output:
| AND Truth Table | Result |
A = False, B = False | A AND B = False |
A = False, B = True | A AND B = False |
A = True, B = False | A AND B = False |
A = True, B = True | A AND B = True |
3. Write a program to implement Half Adder, Full Adder and Parallel Adder.
Source code:
# Half Adder
def half_adder(a, b):
sum = a ^ b # XOR
carry = a & b # AND
return sum, carry
# Full Adder
def full_adder(a, b, carry_in):
s1, c1 = half_adder(a, b)
s2, c2 = half_adder(s1, carry_in)
sum = s2
carry_out = c1 | c2
return sum, carry_out
# Parallel Adder
def parallel_adder(a, b):
assert len(a) == len(b), "Lengths of input arrays do not match"
n = len(a)
carry = 0
result = [0] * n
for i in range(n-1, -1, -1):
sum, carry = full_adder(a[i], b[i], carry)
result[i] = sum
if carry == 1:
result.insert(0, carry)
return result
# Full Adder
sum, carry = full_adder(a[0], b[0], 0)
print("Full Adder")
print("Sum: ", sum) # Output: 0
print("Carry: ", carry) # Output: 1
# Parallel Adder
result = parallel_adder(a, b)
print("Parallel Adder")
print("Result: ", result) # Output: [1, 0, 0, 1, 1]
Output:
Half adder:
Sum 0
Carry 1
Full adder:
Sum 0
Carry 1
Parallel Adder:
Result: [1, 0, 0, 1, 1]
4. Write a GUI program to create a window wizard having two text labels, two text
fields and two buttons as submit and reset.
Source code:
import tkinter as tk
class WindowWizard:
def init (self, master):
self.master = master
master.title("Window Wizard")
def submit(self):
# Get the input values
name = self.entry1.get()
email = self.entry2.get()
def reset(self):
# Clear the input fields
self.entry1.delete(0, tk.END)
self.entry2.delete(0, tk.END)
root = tk.Tk()
window = WindowWizard(root)
root.mainloop()
Output: