Python Programming Lab Manual
Python Programming Lab Manual
0 1 2 2
Course Objectives:
Course Outcomes: After completion of the course, the student should be able to
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.
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 - 2:
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
uppercase 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 - 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 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 - 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.
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 - 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
geometricalshapes and operations on them as its functions.
3. Use the structure of exception handling all general purpose exceptions.
Week-6:
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
a representation 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
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 into a third file.
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.
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. 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
buttons as 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
INTRODUCTION TO PYTHON PROGRAMMING
FEATURES OF PYTHON
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python
is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation, and it has fewer syntactical constructions than other languages.
Python's features include the following –
• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and cross platform
compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has the same
interface on allplatforms.
• Extendable − We can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
• Databases − Python provides interfaces to all major commercial databases.
• GUI Programming − Python supports GUI applications that can be created and ported to
many systemcalls, libraries and windows systems, such as Windows MFC, Macintosh, and the
X Window system ofUnix.
• Scalable − Python provides a better structure and support for large programs than shell scripting.
import webbrowser
open('http://www.python.org')
1. (ii) Start the Python interpreter and type help() to start the
online help utility.
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".
3. (ii)Given coordinates (x1, y1), (x2, y2) find the distance between two
points.
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
WEEK-2
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)
2. Write a program to check whether the given input is digit or lowercase character
or uppercase character or a special character (use 'if-else-if' ladder).
ch = input("Please Enter Your Own Character : ")
if (ch.isupper()):
print("The Given Character ", ch, "is an Uppercase Alphabet")
elif (ch.islower()):
print("The Given Character ", ch, "is a Lowercase Alphabet")
else:
print("The Given Character ", ch, "is Not a Lower or Uppercase Alphabet")
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
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)
WEEK-3
1. (i) Write a program to convert a list and tuple into arrays.
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)
1. (ii) Write a program to find common values
between two arrays
a=[1,2,3,4]
b=[4,5,6,7]
print(set(a).intersection(set(b)))
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]):
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):
return all(lst[i] <= lst[i+1] for i in range(len(lst)-1))
print(is_sorted([5,4,3,2,1]))
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.
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)
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.
with open("words.txt", "a") as f:
f.write("\nI\na\n")
f.write("\n")
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 = {}
n = int(input("Enter the number of key-value pairs in the dictionary: "))
for i in range(n):
key = input("Enter the key: ")
print(inverted)
3. i) Add a comma between the characters. If the given word is ‘Apple’, it should
become ‘A,p,p,l,e’
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?
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)
4. Write a recursive function that generates all binary strings of n-bit length.
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)
Week-5
1. i) Write a python program that defines a matrix and prints
Open a new Python file and save it with a name, for example, "geometry.py".
Define functions that implement different operations on geometrical shapes. For
example, you can define functions for calculating the area and perimeter of a circle,
rectangle, and triangle. Here's an example code for the functions:
import math
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))
3. Use the Structure of Exception hadling all general purpose exceptions using
python
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)
WEEK-6
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): ")
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
# define a point
point = (200, 200)
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
import turtle
class Circle:
def __init__(self, x, y, radius):
self.x = x
self.y = y
self.radius = radius
def __str__(self):
return f"Circle at ({self.x}, {self.y}) with radius {self.radius}"
def draw_circles(circles):
t = turtle.Turtle()
t.speed('fastest')
t.penup()
for circle in circles:
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)
2.Write a Python program to demonstrate the usage of method resolution order (MRO) in
multiple levels of inheritance
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()
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
import re
WEEK-7
1. Write a program to merge two given files contents into the third file
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
# Example usage
file_path = 'example.txt'
words_to_check = ['hello', 'world', 'Python']
check_words_in_file(file_path, words_to_check)
3. Write a python code read text from the text file, find the word with most number of
occurrences from collections import Counter
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
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())
WEEK-8
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.
2. Write a program to implement digital logic gates- AND, OR, NOT, EX-OR
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
Inputs:
x1 (int): The first input to the XOR gate (either 0 or 1).
x2 (int): The second input to the XOR gate (either 0 or 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
3. Write a program to implement Half Adder, Full Adder and Parallel Adder.
# 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]
4. Write a GUI program to create a window wizard having two text labels, two text
fields and two buttons as submit and reset.
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()