Pp Lab Manual
Pp Lab Manual
PYTHON PROGRAMMING[20ES0CS04]
LAB MANUAL
1
GURU NANAK INSTITUTE OF TECHNOLOGY
Guru Nanak Institute of Technoloogy
Ibrahimpatnam, R R District – 501 506.
2
GURU NANAK INSTITUTE OF TECHNOLOGY
INSTRUCTORES :
PROGRAMMER :
VENUE : BLOCK
: CSE
Authorized by
HOD-H&S
3
GURU NANAK INSTITUTE OF TECHNOLOGY
INSTITUTE VISION
4
GURU NANAK INSTITUTE OF TECHNOLOGY
DEPARTMENT VISION
5
GURU NANAK INSTITUTE OF TECHNOLOGY
PEO-1:Graduates shall have the ability to apply knowledge and technical skills across the
disciplines and in emerging areas of Computer Science and Engineering for higher studies, research,
employability, product development and handle realistic problems.
PEO-2:Graduates shall possess managerial skills, maintain ethical conduct, sense of responsibility to
serve the society and to protect the environment.
PEO-3:Graduates shall possess academic excellence with innovative insight, soft skills, leadership
qualities, knowledge of contemporary issues for successful professional career.
B. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics natural science, and engineering sciences.
6
GURU NANAK INSTITUTE OF TECHNOLOGY
E. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
F. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
H. Ethics: Apply ethics principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
L. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
7
GURU NANAK INSTITUTE OF TECHNOLOGY
CourseOutcomes (COs)
8
GURU NANAK INSTITUTE OF TECHNOLOGY
INDEX
Remarks
Sl.No CONTENT Page. No
If any
2 Guidelines to Students 16
5 References 20
9
GURU NANAK INSTITUTE OF TECHNOLOGY
Contents of Lab Manual
10
GURU NANAK INSTITUTE OF TECHNOLOGY
INDEX
12
1 Lab Objective
13
2 Lab outcomes
14
3 Introduction About Lab
Guidelines to students 15
22
8 Text Books / Reference Books
11
GURU NANAK INSTITUTE OF TECHNOLOGY
LAB OBJECTIVE
12
GURU NANAK INSTITUTE OF TECHNOLOGY
Python Programming LAB
2. LAB OUTCOME
13
GURU NANAK INSTITUTE OF TECHNOLOGY
3. INTRODUCTION ABOUT LAB
There are 60 systems (Compaq Presario) installed in this Lab. Their configurations are as
follows:
Software
All systems are configured in DUAL BOOT mode i.e., Students can boot from
Windows XP or Linux as per their lab requirement. This is very useful for students
because they are familiar with different Operating Systems so that they can
execute their programs in different programming environments.
Each student has a separate login for database access Oracle 9i client version is
installed in all systems. On the server, account for each student has been created.
This is very useful because students can save their work (scenarios’, PL / SQL
programs, data related projects, etc) in their own accounts. Each student work is
safe and secure from other students.
14
GURU NANAK INSTITUTE OF TECHNOLOGY
a) Explanation on today’s experiment by the concerned faculty using OHP/PPT covering the
following aspects: 25 mins.
100 mins.
Writing of the experiment in the Observation Book:
The students will write the today’s experiment in the Observation book as per the
following format:
a) Name of the experiment/Aim
b) Software/Hardware required
c) Commands with suitable Options
d) Shell Programs/System call using C-Programs
e) Test Data
a. Valid data sets
b. Limiting value sets
c. Invalid data sets
f) Results for different data sets
g) Viva-Voice Questions and Answers
h) Errors observed (if any) during compilation/execution
15
GURU NANAK INSTITUTE OF TECHNOLOGY
i) Signature of the Faculty
Students are required to carry their lab observation book and record book with completed
experiments while entering the lab.
Students must use the equipment with care. Any damage is caused student is punishable
Students are not allowed to use their cell phones/pen drives/ CDs in labs.
Students need to be maintain proper dress code along with ID Card
Students are supposed to occupy the computers allotted to them and are not supposed to
talk or make noise in the lab.
Students, after completion of each experiment they need to be updated in observation
notes and same to be updated in the record.
Lab records need to be submitted after completion of experiment and get it corrected with
the concerned lab faculty.
If a student is absent for any lab, they need to be completed the same experiment in the
free time before attending next lab.
Step1: Students have to write the date, aim, S/W & H/W requirements for that experiment in the
observation book.
Step2: Students have to listen and understand the experiment explained by the faculty and note
down the important points in the observation book.
Step3: Students need to write procedure/algorithm in the observation book.
Step4: Analyze and Develop/implement the logic of the program by the student in respective
platform
Step5: after approval of logic of the experiment by the faculty then the experiment has to be
executed on the system.
Step6: After successful execution the results are to be shown to the faculty and noted the same in
the observation book.
Step7: Students need to attend the Viva-Voce on that experiment and write the same in the
observation book.
16
GURU NANAK INSTITUTE OF TECHNOLOGY
Step8: Update the completed experiment in the record and submit to the concerned faculty in-
charge.
Before start of the first lab they have to buy the record and bring the record to the lab.
Regularly (Weekly) update the record after completion of the experiment and get it
corrected with concerned lab in-charge for continuous evaluation.
In case the record is lost inform the same day to the faculty in charge and get the new
record within 2 days the record has to be submitted and get it corrected by the faculty.
If record is not submitted in time or record is not written properly, the evaluation marks
(5M) will be deducted.
Record 5 Marks
Equipment in the lab for the use of student community. Students need to maintain a
proper decorum in the computer lab. Students must use the equipment with care. Any
damage is caused is punishable.
Students are required to carry their observation / programs book with completed exercises
while entering the lab.
Students are supposed to occupy the machines allotted to them and are not supposed to
talk or make noise in the lab. The allocation is put up on the lab notice board.
Lab can be used in free time / lunch hours by the students who need to use the systems
should take prior permission from the lab in-charge.
18
GURU NANAK INSTITUTE OF TECHNOLOGY
19
GURU NANAK INSTITUTE OF TECHNOLOGY
Week11.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 21. 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 geometrical
shapes 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 a20
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.
GURU NANAK INSTITUTE OF TECHNOLOGY
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.
6. Reference Books
Comdex Information Technology course tool kit Vikas Gupta, WILEY Dreamtech
The Complete Computer upgrade and repair book, 3rd edition Cheryl A Schmidt,
WILEY Dreamtech
Introduction to Information Technology, ITL Education Solutions limited, Pearson
Education.
PC Hardware - A Handbook – Kate J. Chase PHI (Microsoft)
LaTeX Companion – Leslie Lamport, PHI/Pearson.
21
GURU NANAK INSTITUTE OF TECHNOLOGY
IT Essentials PC Hardware and Software Companion Guide Third Edition by David
Anfinson and Ken Quamme. – CISCO Press, Pearson Education.
IT Essentials PC Hardware and Software Labs and Study Guide Third Edition by Patrick
Regan – CISCO Press, Pearson Education.
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, VamsiKurama, Pearson
2. Python Programming A Modular Approach with Graphics, Database, Mobile, and Web Applications,
SheetalTaneja, 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. Introduction to Python, Kenneth A. Lambert, Cengage
INDEX
S.No Name Of the Experiment Page Numbers
INTRODUCTION TO PYTHON PROGRAMMING
1 24-25
2 WEEK1 26-28
3 WEEK2 29-32
4 WEEK3 33-34
5 WEEK4 35-39
6 WEEK5 40-42
7 WEEK6 43-44
8 WEEK7 45-48
22
GURU NANAK INSTITUTE OF TECHNOLOGY
9 WEEK8 49-53
23
GURU NANAK INSTITUTE OF TECHNOLOGY
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 all
platforms.
• 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.
24
GURU NANAK INSTITUTE OF TECHNOLOGY
• GUI Programming − Python supports GUI applications that can be created and ported to many system
calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of
Unix.
• Scalable − Python provides a better structure and support for large programs than shell scripting.
APPLICATIONS OF PYTHON PROGRAMMING
• • Web Development
• • Game Development
• • Scientific and Numeric applications
• • Artificial Intelligence and Machine Learning based applications
• • Data Science related applications
• • Desktop GUI applications
• • Software Development
• • Enterprise-level/Business Applications
• • Education programs and training courses
• • Web Scraping Applications
• • Image Processing and Graphic Design Applications
• • Data Analysis
25
GURU NANAK INSTITUTE OF TECHNOLOGY
Experiment 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.
CODE:
import webbrowser
webbrowser.open('http://www.python.org')
II. Start the Python interpreter and type help() to start the online help utility.
CODE:
>>> help()
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.9/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".
help>
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)
26
GURU NANAK INSTITUTE OF TECHNOLOGY
elif operator == "/":
print(first / second)
elif operator == "%":
print(first % second)
else:
print("Invalid Operation")
27
GURU NANAK INSTITUTE OF TECHNOLOGY
Output:
Enter first number: 5
Enter second number: 6
----press keys for operator (+,-,*,/,%)----------
Enter operator : +
11
Experiment 3:
i. Write a program to calculate compound interest when principal, rate and number of
periods are given.
CODE:
#Python program to compute compound interest
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time in years: "))
#compute compound interest
compound_interest = principal * ((1 + rate/100) ** time) - principal
#print
print("The compound interest is:", compound_interest)
Output:
Enter the principal amount: 50000
Enter the number of years: 5
Enter the rate of interest: 12
The compound interest is: 88117.08416000004
ii. Given coordinates (x1, y1), (x2, y2) find the distance between two points.
CODE:
# Python Program to Calculate Distance
# Reading co-ordinates
x1 = float(input('Enter x1: '))
y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))
# Calculating distance
d = ( (x2-x1)**2 + (y2-y1)**2 ) ** 0.5
# Displaying result
#print('Distance = %f' %(d))
print("distance between",(x1,x2),"and",(y1,y2),"is : %f" %(d))
28
GURU NANAK INSTITUTE OF TECHNOLOGY
Output:
enter x1 : 15
enter x2 : 10
enter y1 : 4
enter y2 : 22
distance between (15, 10) and (4, 22) is : 18.681541
29
GURU NANAK INSTITUTE OF TECHNOLOGY
Experiment 4: Read name, address, email and phone number of a person through
keyboard and print the details.
CODE:
# read name, contact, email and birthday from user and print them
print("Enter your name: ", end="")
name = input()
print("Enter your phone number: ", end="")
ph_num = input()
print("Enter your email: ", end="")
email = input()
print("Enter your address: ", end="")
address = input()
print("Name: ", name)
print("Phone Number: ", ph_num)
print("Email: ", email)
print("Address: ", address)
Output:
Enter your name: Rahul
Enter your phone number: 1234567890
Enter your email: [email protected]
Enter your address: ibrahimpatnam
Name: Rahul
Phone Number: 1234567890
Email: [email protected]
Address: Ibrahimpatnam
30
GURU NANAK INSTITUTE OF TECHNOLOGY
CODE:
# outer loop
for i in range(0, 5):
count=5;
# nested loop
for j in range(0, i+1):
# display number
print(count-j,end="")
# new line after each row
print("\r")
Output:
5
54
543
5432
54321
Experiment 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).
CODE:
Experiment 3: Python Program to Print the Fibonacci sequence using while loop.
CODE:
# Program to display the Fibonacci sequence up to n-th term
num = int(input("Enter the Fibonacci Number Range: "))
n1 = 0
n2 = 1
Sum = 0
i=0
print("Fibonacci Series:")
while(i < num):
print(n1, end = ' ')
Sum = Sum + n1
Next = n1 + n2
n1 = n2
n2 = Next
i=i+1
Output:
Enter the Fibonacci Number Range: 8
Fibonacci Series:
0 1 1 2 3 5 8 13
Sum of Fibonacci Series Numbers: 33
Experiment 4: Python program to print all prime numbers in a given interval (use break).
CODE:
# Python program to display all the prime numbers within an interval
lower = 1
upper = 50
Output:
Prime numbers between 1 and 50 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
33
GURU NANAK INSTITUTE OF TECHNOLOGY
Experiment 1:
i. Write a program to convert a list and tuple into arrays.
CODE:
import numpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print("List to array: ")
print(np.asarray(my_list))
my_tuple = ([8, 4, 6], [1, 2, 3])
print("Tuple to array: ")
print(np.asarray(my_tuple))
Output:
List to array:
[1 2 3 4 5 6 7 8]
Tuple to array:
[[8 4 6]
[1 2 3]]
34
GURU NANAK INSTITUTE OF TECHNOLOGY
Experiment 2: Write
a function called gcd that takes parameters a and
b and returns their greatest common divisor.
CODE:
def GCD(x, y):
if x > y:
small = y
else:
small = x
a = 60
b = 48
# prints 12
print ("The gcd of 60 and 48 is: ", end="")
print (GCD(60,48))
Output:
The gcd of 60 and 48 is: 12
35
GURU NANAK INSTITUTE OF TECHNOLOGY
lst=[2,4,6,8,10]
print(is_sorted(lst))
OUTPUT:
True
36
GURU NANAK INSTITUTE OF TECHNOLOGY
CODE:
def has_duplicates(lst):
return len(lst) != len(set(lst))
my_list = [1, 2, 3, 2, 4, 1, 5, 3]
result = has_duplicates(my_list)
print(result)
Output:
True
37
GURU NANAK INSTITUTE OF TECHNOLOGY
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 = []
for element in lst:
if element not in unique_elements:
unique_elements.append(element)
return unique_elements
my_list = [1, 2, 3, 2, 4, 1, 5, 3]
result = remove_duplicates(my_list)
print(result)
Output:
[1, 2, 3, 4, 5]
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.
CODE:
def invert_dictionary(dictionary):
inverted_dict = {}
for key, value in dictionary.items():
inverted_dict[value] = key
return inverted_dict
# Read dictionary values from the user
dictionary = {}
n = int(input("Enter the number of key-value pairs in the dictionary: "))
for i in range(n):
key = input("Enter the key: ")
value = input("Enter the value: ")
dictionary[key] = value
Output:
Enter the number of key-value pairs in the dictionary: 5
Enter the key: 1
38
GURU NANAK INSTITUTE OF TECHNOLOGY
Enter the value: a
Enter the key: 2
Enter the value: b
Enter the key: 3
Enter the value: c
Enter the key: 4
Enter the value: d
Enter the key: 5
Enter the value: e
Inverted Dictionary:
a:1
b:2
c:3
d:4
e:5
3. i) Add a comma between the characters. If the given word is 'Apple', it should become
'A,p,p,l,e'
CODE:
# Read the word from the user
word = input("Enter a word: ")
# Add a comma between the characters of the word
word_with_comma = ','.join(word)
# Print the word with comma
print("Word with comma:", word_with_comma)
OTPUT
Enter a word: Apple
Word with comma: A,p,p,l,e
39
GURU NANAK INSTITUTE OF TECHNOLOGY
OUTPPUT:
Enter a string: GNITC
Enter the word to be removed: C
Modified string: GNIT
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?
CODE:
def capitalize_first_letter(sentence):
capitalized_sentence = ""
new_word = True
for char in sentence:
if new_word and char.isalpha():
char = char.upper()
new_word = False
elif not new_word and char.isalpha():
char = char.lower()
elif char.isspace():
new_word = True
capitalized_sentence += char
return capitalized_sentence
OUTPUT:
Enter a sentence: Sanjay hasin esha
Modified sentence: Sanjay Hasin Esha
4. Writes a recursive function that generates all binary strings of n-bit length.
CODE:
def generate_binary_strings(n):
if n == 0:
return ['']
else:
previous_strings = generate_binary_strings(n-1)
40
GURU NANAK INSTITUTE OF TECHNOLOGY
return [string + bit for string in previous_strings for bit in ['0', '1']]
OUTPUT:
Enter the length of binary strings (n): 4
Generated Binary Strings:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
CODE:
41
GURU NANAK INSTITUTE OF TECHNOLOGY
# Define a matrix
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
OUTPUT:
123
456
789
CODE:
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
OUTPUT:
Result:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
OUUTPUT:
Result:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]
CODE:
import geometry
# Calculate the area and perimeter of a rectangle
rectangle_length = 5
rectangle_width = 3
rectangle_area = geometry.rectangle_area(rectangle_length, rectangle_width)
rectangle_perimeter = geometry.rectangle_perimeter(rectangle_length, rectangle_width)
OUTPUT:
Rectangle Area: 15
Rectangle Perimeter: 16
Triangle Area: 12.0
Triangle Perimeter: 12
CODE:
try:
# Code that may raise an exception
numerator = 10
denominator = 0
result = numerator / denominator
# If an exception occurs, the code below this line will not be executed
print("Result:", result)
except ZeroDivisionError:
# Handle ZeroDivisionError exception
print("Error: Cannot divide by zero!")
except ValueError:
# Handle ValueError exception
print("Error: Invalid value!")
except Exception as e:
# Handle any other general-purpose exception
print("Error:", str(e))
else:
# Code to execute if no exception occurs
print("No exception occurred.")
finally:
# Code that always executes, whether an exception occurred or not
print("Finally block executed.")
OUTPUT:
Error: Cannot divide by zero!
Finally block executed.
44
GURU NANAK INSTITUTE OF TECHNOLOGY
CODE:
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
self.grid = [[' ' for _ in range(width)] for _ in range(height)]
def draw(self):
for row in self.grid:
print(' '.join(row))
class Rectangle:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
# Example usage
canvas = Canvas(10, 5)
rectangle = Rectangle(2, 1, 6, 3)
draw_rectangle(canvas, rectangle)
canvas.draw()
OUTPUT:
######
######
######
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.
CODE:
45
GURU NANAK INSTITUTE OF TECHNOLOGY
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
self.grid = [[' ' for _ in range(width)] for _ in range(height)]
def draw(self):
for row in self.grid:
print(' '.join(row))
class Rectangle:
def __init__(self, x, y, width, height, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
# Example usage
canvas = Canvas(10, 5)
rectangle = Rectangle(2, 1, 6, 3, 'red')
draw_rectangle(canvas, rectangle)
canvas.draw()
OUTPUT:
red red red red red red
red red red red red red
red red red red red red
1. Write a Python code to merge two given file contents into a third file.
46
GURU NANAK INSTITUTE OF TECHNOLOGY
CODE:
def merge_files(file1_path, file2_path, output_file_path):
try:
with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2, open(output_file_path, 'w') as
output_file:
content1 = file1.read()
content2 = file2.read()
output_file.write(content1 + content2)
print("Files merged successfully.")
check=open(output_file_path,"r")
print(check.read())
check.close()
except IOError as e:
print(f"An error occurred: {e}")
# Example usage:
file1_path = 'D:\\file1.txt'
file2_path = 'D:\\file2.txt'
output_file_path = 'D:\\merged_file.txt'
merge_files(file1_path, file2_path, output_file_path)
OUTPUT:
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.
CODE:
def check_words_in_file(file_path, words_to_check):
try:
with open(file_path, 'r') as file:
content = file.read()
for word in words_to_check:
47
GURU NANAK INSTITUTE OF TECHNOLOGY
if word in content:
print(f"Found word '{word}' in the file.")
else:
print(f"Word '{word}' not found in the file.")
except IOError as e:
print(f"An error occurred while opening the file: {e}")
# Example usage:
file_path = 'D:\\sample_file.txt'
words_to_check = ['apple', 'banana', 'orange', 'grape']
check_words_in_file(file_path, words_to_check)
OUTPUT:
3. Write a Python code to Read text from a text file, find the word with most number of
occurrences.
CODE:
def find_most_common_word(file_path):
try:
with open(file_path, 'r') as file:
content = file.read().lower() # Convert content to lowercase for case-insensitive
comparison
words = content.split() # Split the content into words
48
GURU NANAK INSTITUTE OF TECHNOLOGY
print("File not found.")
return None, None
except Exception as e:
print(f"An error occurred: {e}")
return None, None
# Example usage:
file_path = 'D:\\sample_file.txt'
most_common_word, occurrences = find_most_common_word(file_path)
OUTPUT:
"C
:\Users\NAG RAJ\PycharmProjects\pythonProject2\venv\Scripts\python.exe"
"C:/Users/NAG RAJ/PycharmProjects/pythonProject2/occurences.py"
The word 'time' appears 3 times in the file.
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.
CODE:
def analyze_file(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
# Count the number of words
words = content.split()
num_words = len(words)
49
GURU NANAK INSTITUTE OF TECHNOLOGY
# Count the number of lowercase and uppercase letters
num_lower_case = sum(1 for char in content if char.islower())
num_upper_case = sum(1 for char in content if char.isupper())
return num_words, num_vowels, num_blank_spaces, num_lower_case, num_upper_case
except FileNotFoundError:
print("File not found.")
return None, None, None, None, None
except Exception as e:
print(f"An error occurred: {e}")
return None, None, None, None, None
# Example usage:
file_path = 'D:\\file1.txt'
num_words, num_vowels, num_blank_spaces, num_lower_case, num_upper_case =
analyze_file(file_path)
OUTPUT:
Number of words: 3
Number of vowels: 6
Number of blank spaces: 2
Number of lowercase letters: 16
Number of uppercase letters: 1
50
GURU NANAK INSTITUTE OF TECHNOLOGY
CODE:
import numpy as np
import matplotlib.pyplot as plt
import scipy
# Numpy
arr = np.array([1, 2, 3, 4, 5])
mean = np.mean(arr)
std_dev = np.std(arr)
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix_transpose = np.transpose(matrix)
values = np.linspace(0, 10, 100)
squared_values = np.square(values)
# Matplotlib
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Function")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
x_scatter = np.random.rand(50)
y_scatter = np.random.rand(50)
plt.scatter(x_scatter, y_scatter)
plt.title("Scatter Plot")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
# Scipy
from scipy.optimize import minimize
def quadratic(x):
return x**2 + 3*x + 2
51
GURU NANAK INSTITUTE OF TECHNOLOGY
from scipy.interpolate import interp1d
x_interp = np.linspace(0, 10, num=11, endpoint=True)
y_interp = np.cos(-x_interp**2/9.0)
f = interp1d(x_interp, y_interp, kind='cubic')
CODE:
import numpy as np
# Create a 1D array
arr1d = np.array([1, 2, 3, 4, 5])
# Array manipulation
arr2d_transposed = np.transpose(matrix)
# Generating sequences
values = np.linspace(0, 10, 100) # Generates 100 values between 0 and 10
# Element-wise operations
squared_values = np.square(values)
# Mathematical operations
result = np.sin(arr1d)
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
CODE:
# Implementing Digital Logic Gates in Python
# OR gate function
def OR(a, b):
return a or b
# Display results
print("AND Gate:", and_result)
print("OR Gate:", or_result)
print("NOT Gate:", not_result)
print("XOR Gate:", xor_result)
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
53
GURU NANAK INSTITUTE OF TECHNOLOGY
CODE:
5. Write a GUI program to create a window wizard having two text labels, two text fields
and two buttons as Submit and Reset.
CODE:
import tkinter as tk
from tkinter import messagebox
# Labels
name_label = tk.Label(root, text="Name:")
age_label = tk.Label(root, text="Age:")
# Entry fields
name_entry = tk.Entry(root)
age_entry = tk.Entry(root)
# Buttons
submit_button = tk.Button(root, text="Submit", command=submit_click)
reset_button = tk.Button(root, text="Reset", command=reset_click)
54
GURU NANAK INSTITUTE OF TECHNOLOGY
# Start the GUI event loop
root.mainloop()
OUTPUT:
55
GURU NANAK INSTITUTE OF TECHNOLOGY
print("Ideas won't work unless we do...")
print('Ideas will not work unless we do...')
print('''Ideas won't work
unless we do....''')
Output:
Ideas won't work unless we do...
Ideas will not work unless we do...
Ideas won't work
unless we do....
Output:
HelloWorld
HelloWorld
Hello World
Hello World
HelloWorld
56
GURU NANAK INSTITUTE OF TECHNOLOGY
Output:
Ideas Won't work unless we do...
Output:
Type of variable i= <class 'int'>
Type of variable i= <class 'float'>
Type of variable i= <class 'str'>
57
GURU NANAK INSTITUTE OF TECHNOLOGY
Write a python program to convert temperature in Celsius to Fahrenheit
SOURCE CODE:
# change this value for a different result
celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
Output:
37.5 degree Celsius is equal to 99.5 degree Fahrenheit
Output:
5.0
5.0
5
12
6
4
125.0
58
GURU NANAK INSTITUTE OF TECHNOLOGY
3.141592653589793
2.718281828459045
120
720
1
1
45.89
98.0
0.49999999999999994
0.5000000000000001
0.9999999999999999
0.0
1.3862943611198906
Write a python program to print date, time for today and now.
SOURCE CODE:
import datetime
a=datetime.datetime.today()
b=datetime.datetime.now()
print(a)
print(b)
Output:
2023-11-19 18:23:34.039234
2023-11-19 18:23:34.039234
Write a program that accepts the lengths of three sides of a triangle as input the program output
should indicate whether or not the triangle ,is right triangle(recall from the Pythagorean theorem
that in a right triangle ,the square of one side equals the sum of the squares of the other two
sides)
SOURCE CODE:
print("Input lengths of the triangle sides: ")
x = int(input("x: "))
y = int(input("y: "))
z = int(input("z: "))
if x == y == z:
print("Equilateral triangle")
elif x==y or y==z or z==x:
print("isosceles triangle")
else:
print("Scalene triangle")
Output:
Input lengths of the triangle sides:
x: 6
59
GURU NANAK INSTITUTE OF TECHNOLOGY
y: 8
z: 12
Scalene triangle
Output:
Enter First number: 10
Enter Second number 5
Sum of 10 and 5 is : 15
Difference of 10 and 5 is : 5
Product of 10 and 5 is : 50
Division of 10 and 5 is : 2.0
Floor Division of 10 and 5 is : 2
Exponent of 10 and 5 is : 100000
Modulus of 10 and 5 is : 0
Output:
Enter a number:10
n is even
Enter a number:7
Write a python program to print a number is even using simple if –else statement
60
GURU NANAK INSTITUTE OF TECHNOLOGY
SOURCE CODE:
n=int(input("Enter a number:"))
if(n%2==0):
print("n is even")
else:
print("n is odd")
Output:
Enter a number:10
n is even
Enter a number:7
n is odd
Write a python program to find the greater number between two numbers.
SOURCE CODE:
A=int(input("enter A:"))
B=int(input("enter B:"))
if(A>B):
print("A is greater")
else:
rint("B is greater")
Output:
enter A:3
enter B:6
B is greater
Write a python program to print the factorial of a number using if-elif-else ladder
SOURCE CODE:
n=int(input("Enter a number:"))
factorial=1
i=1
if(n<0):
print("Sorry factorial numbers doesn't exist for negative numbers")
elif(n==0):
print("Factorial of 0 is 0")
else:
for i in range(1,n+1):
factorial = factorial * i
print("Factorial of", n, "is", factorial)
Output:
1)Enter a number:5
Factorial of 5 is 120
61
GURU NANAK INSTITUTE OF TECHNOLOGY
2) Enter a number:0
Factorial of 0 is 0
3) Enter a number:-2
Sorry factorial numbers doesn't exist for negative numbers
Write a python program to print the sum of digits of a number using while loop
SOURCE CODE:
n=int(input("enter a number"))
sum=0
while(n>0):
r = n % 10
sum = sum + r
n = n // 10
print("sod",sum)
Input& Output:
Enter a number:2356
sod= 16
Write a python program to print the reverse of a number using while loop
SOURCE CODE:
n=int(input("Enter a number:"))
rev=0
while(n>0):
r = n % 10
rev = rev*10 + r
n = n // 10
print("Reverse of number=",rev)
Input& Output:
Enter a number:234
Reverse of number= 432
Write a python program to print the palindrome of a number using while loop
SOURCE CODE:
n=int(input("Enter a number:"))
rev=0
temp=n
while(n>0):
r = n % 10
rev = rev*10 + r
n = n // 10
if (temp==rev):
print(rev,"is a palindrome")
else:
print(rev, "is not a palindrome")
62
GURU NANAK INSTITUTE OF TECHNOLOGY
Input& Output:
1) Enter a number:121
121 is a palindrome
2) Enter a number:234
432 is not a palindrome
Input& Output:
1) Enter a number:125
125 is an Armstrong Number
2) Enter a number:153
153 is an Armstrong Number
Write a python program to print whether the given number is prime or not using for loop
SOURCE CODE1:
n=int(input("Enter a number:"))
for i in range(2,n):
if(n%i==0):
print(n,"is not a prime number")
break
else:
print(n, "is a prime number")
Input& Output:
1)Enter a number:6
6 is not a prime number
2) Enter a number:11
11 is a prime number
SOURCE CODE2:
n=int(input("Enter a number:"))
count=0
63
GURU NANAK INSTITUTE OF TECHNOLOGY
for i in range(1,n+1):
if(n%i==0):
count+=1
if(count>2):
print(n, "is not a prime number")
break
else:
print(n, "is a prime number")
Input& Output:
1)Enter a number:6
6 is not a prime number
2)Enter a number:7
7 is a prime number
Output:
Enter the number: 20
Prime numbers between 1 and 20 are:
2
3
5
7
11
13
17
19
Write a program to create, concatenate and print a string and accessing sub-string from given
string
#create string
64
GURU NANAK INSTITUTE OF TECHNOLOGY
# all of the following are equivalent
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
Output:
Hello
Hello
Hello
Hello, welcome to
the world of Python
print string:
#concatenate
str1 = 'Hello'
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
str = 'NagarajU'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
Output:
str1 + str2 = HelloWorld!
str1 * 3 = HelloHelloHello
str = NagarajU
str[0] = N
str[-1] = U
65
GURU NANAK INSTITUTE OF TECHNOLOGY
Output:
GNIMMARGORP NOHTYP
PYTHON PROGRAMMING
GIMROPNHY
GAPT
T
H
AGR
ON PRO
66
GURU NANAK INSTITUTE OF TECHNOLOGY
O
GRN
TYP
IMROPNHY
HY
PROGRAMMIN
SOURCE CODE:
a=[1,3,5,6,7,[3,4,5],"hello"]
print(a)
a.insert(3,20)
print(a)
a.remove(7)
print(a)
a.append("hi")
print(a)
len(a)
print(a)
a.pop()
print(a)
a.pop(6)
print(a)
a.clear()
print(a)
Output:
67
GURU NANAK INSTITUTE OF TECHNOLOGY
[1, 3, 5, 6, 7, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, 7, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, [3, 4, 5], 'hello', 'hi']
[1, 3, 5, 20, 6, [3, 4, 5], 'hello', 'hi']
[1, 3, 5, 20, 6, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, [3, 4, 5]]
[]
68