0% found this document useful (0 votes)
4 views56 pages

Civil Python Lab Manual

The document outlines the syllabus for a Python Programming Laboratory course for B.Tech Civil Engineering students in Semester III. It includes course objectives, outcomes, and a detailed weekly schedule of lab experiments that cover various Python programming concepts and applications. The document also lists required textbooks and reference materials for the course.

Uploaded by

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

Civil Python Lab Manual

The document outlines the syllabus for a Python Programming Laboratory course for B.Tech Civil Engineering students in Semester III. It includes course objectives, outcomes, and a detailed weekly schedule of lab experiments that cover various Python programming concepts and applications. The document also lists required textbooks and reference materials for the course.

Uploaded by

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

B.

TECH CIVIL ENGINEERING – R22


PYTHON PROGRAMMING LABORATORY (D2ESPP1)
SEMESTER III
Course Objectives:
1. To install and run the Python interpreter
2. To learn control structures.
3. To Understand Lists, Dictionaries in python
4. To Handle Strings and Files in Python
Course Outcomes: After completion of the course, the student should be able to
1. Develop the application specific codes using python.
2. Understand Strings, Lists, Tuples and Dictionaries in Python
3. Verify programs using modular approach, file I/O, Python standard library
4. Implement Digital Systems using Python.
Note: The lab experiments will be like the following experiment examples

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. Write a program to calculate compound interest when principal, rate and numbers of
periods are given.
i) 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
2 2 22
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.
3. 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.
4. The wordlist I provided, words.txt, doesn’t contain single letter words. So you might want
to add “I”, “a”, and the empty string.
5. 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.
6. Add a comma between the characters. If the given word is 'Apple', it should become
'A,p,p,l,e'
7. Remove the given word in all the places in a string?
8. 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?
9. Writes a recursive function that generates all binary strings of n-bit length
Week - 5:
1. Write a python program
i) that defines a matrix and prints
ii) to perform addition of two square matrices
iii) 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. Do the following:
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.
e) 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. 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.
PYTHON LAB MANUAL
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.

How to Access Python Documentation at python.org

1. Open a web browser (like Chrome, Firefox, or Edge).


2. In the address bar, type:
http://python.org
and press Enter.
3. On the homepage, look at the top menu bar and click on:
“Docs” (short for Documentation).
4. You’ll be taken to the Python Documentation page:
https://docs.python.org
5. From here, you can:
o 📘 View documentation for different Python versions (like 3.13, 3.12, etc.)
o 🔍 Use the search bar at the top-right to find help on specific topics (e.g., “for
loops”, “functions”, “file handling”).
o 📚 Access tutorials, library references, install guides, and FAQs.

Example:

To read the Python 3 Tutorial:

 Go to: https://docs.python.org/3/tutorial/

ii) Start the Python interpreter and type help() to start the online help utility.

How to Start the Python Interpreter and Use help()

a. Open your terminal or command prompt:


o On Windows: Press Windows + R, type cmd, and hit Enter.
o On macOS/Linux: Open the Terminal from the applications or menu.
b. Start the Python interpreter by typing:

bash
CopyEdit
python

(or python3 if python doesn't work)

c. You’ll see something like this:

cpp
CopyEdit
Python 3.13.5 (default, ...)
Type "help", "copyright", "credits" or "license" for more
information.
>>>

d. At the >>> prompt, type:

python
CopyEdit
help()

and press Enter.

e. You will enter the Python help utility. It looks like this:

csharp
CopyEdit
Welcome to Python 3.13'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/tutorial/

help>

f. You can now:


o Type a topic (like str, list, for, or modules) to get help on that subject.
o Type modules to see available modules.
o Type keywords to see reserved keywords.
o Type quit to exit the help utility.

g. To exit Python itself, type:


python
CopyEdit
exit()

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

Steps to Use Python as a Calculator

a. Open your terminal or command prompt:


o Windows: Press Windows + R, type cmd, press Enter.
o macOS/Linux: Open the Terminal.
b. Start the Python interpreter by typing:

nginx
CopyEdit
python

(or python3 if needed)

c. Once you see the prompt >>>, you can start typing math expressions just like on a
calculator:
Example
python
CopyEdit
>>> 2 + 3
5

>>> 10 - 4
6

>>> 6 * 7
42

>>> 20 / 4
5.0

>>> 2 ** 3 # Exponentiation
8

>>> 15 % 4 # Modulo (remainder)


3

d. You can also use parentheses to group operations:

python
CopyEdit
>>> (2 + 3) * 4
20

e. To exit the interpreter, type:

python
CopyEdit
exit()

3. Write a program to calculate compound interest when principal, rate and numbers
of periods are given.
# Python3 program to find compound
# interest for given values.
def compound_interest(principal, rate, time):
# Calculates compound interest
Amount = principal * (pow((1 + rate / 100), time))
CI = Amount - principal
print("Compound interest is", CI)
# Driver Code
compound_interest(10000, 10.25, 5)
i) Given coordinates (x1, y1), (x2, y2) find the distance between two points
# Python3 program to calculate
# distance between two points
import math
# Function to calculate distance
def distance(x1 , y1 , x2 , y2):
# Calculating distance
return math.sqrt(math.pow(x2 - x1, 2) +
math.pow(y2 - y1, 2) * 1.0)
# Drivers Code
print("%.6f"%distance(3, 4, 4, 3))
Read name, address, email and phone number of a person through keyboard and print the
details
# carrier: to know the name of
# service provider of that phone number
from phone numbers import carrier
service_provider = phone numbers.parse("Number with country code")
# Indian phone number example: +91**********
# Nepali phone number example: +977**********
# this will print the service provider name
print(carrier.name_for_number(service_provider, 'en'))
Print the below triangle using for loop.
# Python 3.x code to demonstrate star pattern
# Function to demonstrate printing pattern
def pypart(n):
# outer loop to handle number of rows
# n in this case
for i in range(0, n):
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ",end="")
# ending line after each row
print("\r")
# Driver Code
n=5
pypart(n)

4. Read name, address, email and phone number of a person through keyboard and
print the details.
# Read user input
name = input("Enter your name: ")
address = input("Enter your address: ")
email = input("Enter your email: ")
phone = input("Enter your phone number: ")
# Print the details
print("\n--- Person Details ---")
print("Name :", name)
print("Address :", address)
print("Email :", email)
print("Phone No. :", phone)
Output:
Enter your name: Priya Sharma
Enter your address: 123, MG Road, Mumbai
Enter your email: [email protected]
Enter your phone number: 9876543210
--- Person Details ---
Name : Priya Sharma
Address : 123, MG Road, Mumbai
Email : [email protected]
Phone No. : 9876543210
Week - 2:
1. Print the below triangle using for loop.
5
44
333
2 2 22
11111

# Loop from 5 down to 1


for i in range(5, 0, -1):
for j in range(5, i - 1, -1):
print(i, end=" ")
print()

Output:
5
4 4
3 3 3
2 2 2 2
1 1 1 1 1

This code uses two nested for loops:

 The outer loop sets the number to be printed.


 The inner loop controls how many times the number is printed on each line.
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)

string = 'GeeksforGeeks is a computer Science portal for Geeks'

newstring = ''

count1 = 0

count2 = 0

count3 = 0

for a in string:

# Checking for lowercase letter and

# converting to uppercase.

if (a.isupper()) == True:

count1 += 1

newstring += (a.lower())

# Checking for uppercase letter and

# converting to lowercase.

elif (a.islower()) == True:

count2 += 1

newstring += (a.upper())

# Checking for whitespace letter and

# adding it to the new string as it is.

elif (a.isspace()) == True:

count3 += 1

newstring += a

print("In original String : ")

print("Uppercase -", count1)


print("Lowercase -", count2)

print("Spaces -", count3)

print("After changing cases:")

print(newstring)

Output:
In original String :
Uppercase - 4
Lowercase - 41
Spaces - 7
After changing cases:
gEEKSFORgEEKS IS A COMPUTER sCIENCE PORTAL FOR gEEKS

3. Python Program to Print the Fibonacci sequence using while loop


# Set the number of terms to print
n = int(input("Enter the number of Fibonacci terms: "))
# First two terms
a, b = 0, 1
count = 0
# Print Fibonacci sequence
print("Fibonacci sequence:")
while count < n:
print(a, end=" ")
a, b = b, a + b
count += 1

Output:

Enter the number of Fibonacci terms: 7


Fibonacci sequence:
0 1 1 2 3 5 8
4. Python program to print all prime numbers in a given interval (use break)
# Python3 program to display Prime numbers till N
#function to check if a given number is prime
def isPrime(n):
#since 0 and 1 is not prime return false.
if(n==1 or n==0):
return False
#Run a loop from 2 to n-1
for i in range(2,n):
#if the number is divisible by i, then n is not a prime number.
if(n%i==0):
return False
#otherwise, n is prime number.
return True
# Driver code
N = 100;
#check for every number from 1 to N
for i in range(1,N+1):
#check if current number is prime
if(isPrime(i)):
print(i,end=" ")

Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Week - 3:
1. i) Write a program to convert a list and tuple into arrays.
import numpy as np
# list
list1 = [1, 2, 3]
print(type(list1))
print(list1)
print()
# conversion
array1 = np.array(list1)
print(type(array1))
print(array1)
print()
tuple1 = ((1, 2, 3))
print(type(tuple1))
print(tuple1)
print()
# conversion
array2 = np.array(tuple1)
print(type(array2))
print(array2)
print()
# list, array and tuple
array3 = np.array([tuple1, list1, array2])
print(type(array3))
print(array3)
Output:
<class 'list'>
[1, 2, 3]
<class 'numpy.ndarray'>
[1 2 3]
<class 'tuple'>
(1, 2, 3)
<class 'numpy.ndarray'>
[1 2 3]
<class 'numpy.ndarray'>
[[1 2 3]
[1 2 3]
[1 2 3]]

ii) Write a program to find common values between two arrays.


import numpy as np
ar1 = np.array([12, 14, 15, 16, 17])
ar2 = [2, 4, 5, 6, 7, 8, 9, 12]
# Common values between two arrays
print(np.intersect1d(ar1, ar2))
Output:
[12]
2. Write a function called gcd that takes parameters a and b and returns their greatest
common divisor.
# Python code to demonstrate naive
# method to compute gcd ( Loops )
def computeGCD(x, y):
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
# prints 12
print ("The gcd of 60 and 48 is : ", end="")
print (computeGCD(60,48))
Output
The gcd of 60 and 48 is : 12

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.
# function to check string is
# palindrome or not
def isPalindrome(str):
# Run loop from 0 to len/2
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True
# main function
s = "malayalam"
ans = isPalindrome(s)
if (ans):
print("Yes")
else:
print("No")
Output
Yes

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.
# Python3 code to demonstrate
# to check if list is sorted
# using all()
# initializing list
test_list = [9, 4, 5, 8, 10]
# printing original list
print ("Original list : " + str(test_list))
# using all() to
# check sorted list
flag = 0
if(all(test_list[i] <= test_list[i + 1] for i in range(len(test_list)-1))):
flag = 1
# printing result
if (flag) :
else :
print ("Yes, List is sorted.")
print ("No, List is not sorted.")
Output :
Original list : [9, 4, 5, 8, 10]
No, List is not sorted.

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_dup(v):
c=0
for i in range(len(v)):
for j in range(len(v)-1):
print(f'index:{i} item:{v[i]} with index:{j+1} item:{v[j+1]}')
if v[i] == v[j+1]:
c = c+1
print(c)
if c > 1:
return True
if c <= 1:
return False
v = ['car', 'bar', 'are']
has_dup(v)

# Python program to remove duplicate character


# from character array and print in sorted
# order
def removeDuplicate(str, n):
s = set()
# Create a set using String characters
for i in str:
s.add(i)
# Print content of the set
st = ""
for i in s:
st = st+i
return st
# Driver code
str = "geeksforgeeks"
n = len(str)
print(removeDuplicate(list(str), n))
# This code is contributed by rajsanghavi9.

3. 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.
# Python program to read
# file word by word
# opening the text file
with open('GFG.txt','r') as file:
# reading each line
for line in file:
# reading each word
for word in line.split():
# displaying the words
print(word)
# Open the file in write mode
f2 = open("output2.txt", "w")
# Open the input file again and get
# the content as list to a variable data
with open("file.txt", "r") as myfile:
data = myfile.readlines()
# We will just reverse the
# array using following code
data_2 = data[::-1]
# Now we will write the fully reverse
# list in the output2 file using
# following command
f2.writelines(data_2)
f2.close()

# Python3 code to demonstrate working of


# Adding comma between numbers
# Using str.format()
# initializing number
test_num = 1234567
# printing original number
print("The original number is : " + str(test_num))
# Using str.format()
# Adding comma between numbers
res = ('{:,}'.format(test_num))
# printing result
print("The number after inserting commas : " + str(res))

# Initializing String
test_str = "GeeksForGeeks"
# Removing char at pos 3
# using replace
new_str = test_str.replace('e', '')
# Printing string after removal
# removes all occurrences of 'e'
print ("The string after removal of i'th character( doesn't work) : " + new_str)
# Removing 1st occurrence of s, i.e 5th pos.
# if we wish to remove it.
new_str = test_str.replace('s', '', 1)
# Printing string after removal
# removes first occurrences of s
print ("The string after removal of i'th character(works) : " + new_str)

4. The wordlist I provided, words.txt, doesn’t contain single letter words. So you might
want to add “I”, “a”, and the empty string
# Python3 implementation of the
# above approach
# Function to print the output
def printTheArray(arr, n):
for i in range(0, n):
print(arr[i], end = " ")
print()
of n-bit length
if i == n:
1. Writes a recursive function that generates all binary strings of n-bit length
# Function to generate all binary strings
def generateAllBinaryStrings(n, arr, i):
if i == n:
printTheArray(arr, n)
return
# First assign "0" at ith position
# and try for all other permutations
# for remaining positions
arr[i] = 0
generateAllBinaryStrings(n, arr, i + 1)
# And then assign "1" at ith position
# and try for all other permutations
# for remaining positions
arr[i] = 1
generateAllBinaryStrings(n, arr, i + 1)
# Driver Code
if name == " main ":
n=4
arr = [None] * n
# Print all binary strings
generateAllBinaryStrings(n, arr, 0)
# This code is contributed
# by Rituraj Jain
Output:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
5. 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):
# Invert the dictionary
inverted = {}
for key, value in d.items():
if value in inverted:
# If value already exists as a key, convert it to a list to handle duplicates
if isinstance(inverted[value], list):
inverted[value].append(key)
else:
inverted[value] = [inverted[value], key]
else:
inverted[value] = key
return inverted
# Read dictionary from user
n = int(input("Enter the number of items in the dictionary: "))
user_dict = {}
for _ in range(n):
k = input("Enter key: ")
v = input("Enter value: ")
user_dict[k] = v
# Print original dictionary
print("\nOriginal Dictionary:", user_dict)
# Invert and print
inverted = invert_dict(user_dict)
print("Inverted Dictionary:", inverted)
Output:
Enter the number of items in the dictionary: 3
Enter key: a
Enter value: 1
Enter key: b
Enter value: 2
Enter key: c
Enter value: 1
Original Dictionary: {'a': '1', 'b': '2', 'c': '1'}
Inverted Dictionary: {'1': ['a', 'c'], '2': 'b'}

6. Add a comma between the characters. If the given word is 'Apple', it should become
'A,p,p,l,e'
# Read word from user
word = input("Enter a word: ")
# Add comma between characters
result = ','.join(word)
# Print the result
print("Output:", result)
Output:
Enter a word: Apple
Output: A,p,p,l,e

7. Remove the given word in all the places in a string?


# Read input string and word to remove
text = input("Enter the original string: ")
word_to_remove = input("Enter the word to remove: ")
# Remove the word from the string
result = text.replace(word_to_remove, '')
# Optionally strip extra spaces (optional cleanup)
result = ' '.join(result.split())
# Print the final string
print("Resulting string:", result)
Output:
Enter the original string: Python is fun. Python is easy to learn.
Enter the word to remove: Python
Resulting string: is fun. is easy to learn.

8. 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?
def capitalize_words(sentence):
result = ""
i=0
length = len(sentence)

while i < length:


# Skip spaces and copy them directly
if sentence[i] == ' ':
result += ' '
i += 1
else:
# First letter of the word — convert to uppercase manually
ch = sentence[i]
if 'a' <= ch <= 'z':
result += chr(ord(ch) - 32) # Convert to uppercase
else:
result += ch
i += 1
# Rest of the letters in the word — convert to lowercase manually
while i < length and sentence[i] != ' ':
ch = sentence[i]
if 'A' <= ch <= 'Z':
result += chr(ord(ch) + 32) # Convert to lowercase
else:
result += ch
i += 1
return result
# Example usage
sentence = input("Enter a sentence: ")
output = capitalize_words(sentence)
print("Formatted sentence:", output)

Output:
Enter a sentence: hELLo WOrLD fROM pYTHON
Formatted sentence: Hello World From Python

9. Writes a recursive function that generates all binary strings of n-bit length

def generate_binary_strings(n, prefix=""):


if n == 0:
print(prefix)
return
generate_binary_strings(n - 1, prefix + "0")
generate_binary_strings(n - 1, prefix + "1")

# Example usage:
n=3
generate_binary_strings(n)
Explanation:
n is the number of bits you want in the binary strings.
prefix is used to build each string step by step.
Base case: when n == 0, the current prefix is a complete binary string, so we print it.
Recursive case: append "0" and "1" to the prefix, and reduce n by 1.
Output for n = 3:
Copy
Edit
000
001
010
011
100
101
110
111

Week - 5:
1. Write a python program
i) that defines a matrix and prints
# A basic code for matrix input from user
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("Enter the entries rowwise:")
# For user input
for i in range(R): # A for loop for row entries
a =[]
for j in range(C): # A for loop for column entries
a.append(int(input()))
matrix.append(a)
# For printing the matrix
for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
print()
Output:
Enter the number of rows:2
Enter the number of columns:3
Enter the entries rowwise:
1
2
3
4
5
6
123
456
ii) to perform addition of two square matrices
# Define two square matrices
A=[
[1, 2],
[3, 4]
]
B=[
[5, 6],
[7, 8]
]
# Initialize result matrix with zeros
n = len(A)
result = [[0 for _ in range(n)] for _ in range(n)]
# Perform matrix addition
for i in range(n):
for j in range(n):
result[i][j] = A[i][j] + B[i][j]
# Display the result
print("Sum of the matrices:")
for row in result:
print(row)
Output:
Sum of the matrices:
[6, 8]
[10, 12]

iii) to perform multiplication of two square matrices


# Define two square matrices
A=[
[1, 2],
[3, 4]
]
B=[
[5, 6],
[7, 8]
]
# Size of the square matrix
n = len(A)
# Initialize the result matrix with zeros
result = [[0 for _ in range(n)] for _ in range(n)]
# Perform matrix multiplication
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += A[i][k] * B[k][j]
# Display the result
print("Product of the matrices:")
for row in result:
print(row)
Output:
Product of the matrices:
[19, 22]
[43, 50]

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.

How do you make a module in Python

A module in Python is simply a .py file that contains functions, variables, or classes. You
can import and use them in other Python programs.

Steps to Create a Module:

1. Create a new file with the name geometry.py


2. Define functions related to geometrical shapes (e.g., area, perimeter)
3. Import this module in another Python file and use its functions

1. Create the module


pythonCopyEdit
# geometry.py

import math

def area_circle(radius):
return math.pi * radius ** 2

def perimeter_circle(radius):
return 2 * math.pi * radius

def area_rectangle(length, width):


return length * width

def perimeter_rectangle(length, width):


return 2 * (length + width)

def area_triangle(base, height):


return 0.5 * base * height

2: Use the module


# main.py
import geometry
# Using functions from the geometry module
print("Area of Circle:", geometry.area_circle(5))
print("Perimeter of Circle:", geometry.perimeter_circle(5))
print("Area of Rectangle:", geometry.area_rectangle(4, 6))
print("Perimeter of Rectangle:", geometry.perimeter_rectangle(4, 6))
print("Area of Triangle:", geometry.area_triangle(3, 7))
Output:
Area of Circle: 78.53981633974483
Perimeter of Circle: 31.41592653589793
Area of Rectangle: 24
Perimeter of Rectangle: 20
Area of Triangle: 10.5
3. Use the structure of exception handling all general purpose exceptions.

Exception Handling in Python (General Purpose)

Python provides a structured way to handle errors (called exceptions) using the try, except,
else, and finally blocks.

try:

# Code that might raise an exception

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))


result = num1 / num2

print("Result:", result)

except ZeroDivisionError:

print("❌ Cannot divide by zero!")

except ValueError:

print("❌ Invalid input! Please enter numeric values.")

except Exception as e:

print(f"❌ An unexpected error occurred: {e}")

else:

print("✅ Operation completed successfully.")

finally:

print("📌 This block always runs (e.g., cleanup, closing files).")

How it works:

try: Code that might throw an error

except ZeroDivisionError: Catches divide-by-zero errors

except ValueError: Catches non-numeric input errors

except Exception: Catches all other general errors

else: Runs if no exception is raised

finally: Always runs (good for cleanup)

Output

Enter first number: 10

Enter second number: 0

❌ Cannot divide by zero!

📌 This block always runs (e.g., cleanup, closing files).


Week-6:
1. Do the following:
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.
# draw Rectangle in Python Turtle
import turtle
t = turtle.Turtle()
l = int(input("Enter the length of the Rectangle: "))
w = int(input("Enter the width of the Rectangle: "))
# drawing first side
t.forward(l) # Forward turtle by l units
t.left(90) # Turn turtle by 90 degree
# drawing second side
t.forward(w) # Forward turtle by w units
t.left(90) # Turn turtle by 90 degree
# drawing third side
t.forward(l) # Forward turtle by l units
t.left(90) # Turn turtle by 90 degree
# drawing fourth side
t.forward(w) # Forward turtle by w units
t.left(90) # Turn turtle by 90 degree
Input :
100
120
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.
# Python program to explain cv2.rectangle() method
# importing cv2
import cv2
# path
path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'
# Reading an image in default mode
image = cv2.imread(path)
# Window name in which image is displayed
window_name = 'Image'
# Start coordinate, here (5, 5)
# represents the top left corner of rectangle
start_point = (5, 5)
# Ending coordinate, here (220, 220)
# represents the bottom right corner of rectangle
end_point = (220, 220)
# Blue color in BGR
color = (255, 0, 0)
# Line thickness of 2 px
thickness = 2
# Using cv2.rectangle() method
# Draw a rectangle with blue line borders of thickness of 2 px
image = cv2.rectangle(image, start_point, end_point, color, thickness)
# Displaying the image
cv2.imshow(window_name, image)
import arcade
# Open the window
arcade.open_window(600, 600, "Draw a point for GfG ")
arcade.set_background_color(arcade.color.BLUE)
# Start the render process
arcade.start_render()
# Draw a point
arcade.draw_point(60, 495, arcade.color.RED, 10)
# Draw a point
arcade.draw_point(80, 500, arcade.color.YELLOW, 10)
# Finish the render.
arcade.finish_render()
# Keep the window up until someone closes it.
arcade.run()
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.
# Define Point class
class Point:
def __init__(self, x, y):
self.x = x # column
self.y = y # row
# Reuse create_canvas and print_canvas functions
def create_canvas(rows, cols):
return [[' ' for _ in range(cols)] for _ in range(rows)]
def print_canvas(canvas):
for row in canvas:
print(''.join(row))
# Function to draw a point on the canvas
def draw_point(canvas, point):
if 0 <= point.y < len(canvas) and 0 <= point.x < len(canvas[0]):
canvas[point.y][point.x] = '*'
else:
print("Point is outside the canvas.")
# Example usage
canvas = create_canvas(10, 20)
p1 = Point(5, 3)
p2 = Point(10, 7)
draw_point(canvas, p1)
draw_point(canvas, p2)
print_canvas(canvas)
Output:

d) Define a new class called Circle with appropriate attributes and instantiate a few
Circle objects.
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def circumference(self):
return 2 * math.pi * self.radius
# Instantiate a few Circle objects
circle1 = Circle(5)
circle2 = Circle(10)
circle3 = Circle(2.5)
# Print details
print("Circle 1 - Radius:", circle1.radius, "Area:", circle1.area(), "Circumference:",
circle1.circumference())
print("Circle 2 - Radius:", circle2.radius, "Area:", circle2.area(), "Circumference:",
circle2.circumference())
print("Circle 3 - Radius:", circle3.radius, "Area:", circle3.area(), "Circumference:",
circle3.circumference())

Explanation:

 __init__ method: Initializes a Circle object with a given radius.


 area method: Returns the area of the circle.
 circumference method: Returns the circumference.
e) Write a function called draw_circle that draws circles on the canvas.
class Circle:
def __init__(self, x, y, radius, color='black'):
self.x = x # x-coordinate of the center
self.y = y # y-coordinate of the center
self.radius = radius
self.color = color
class Canvas:
def draw_circle(self, circle):
print(f"Drawing a circle at ({circle.x}, {circle.y}) with radius {circle.radius} and color
{circle.color}")
def draw_circle(canvas, circle):
canvas.draw_circle(circle)
# Example usage:
canvas = Canvas()
circle1 = Circle(100, 150, 50, 'blue')
circle2 = Circle(200, 250, 30, 'red')
draw_circle(canvas, circle1)
draw_circle(canvas, circle2)

2. Write a Python program to demonstrate the usage of Method Resolution Order


(MRO) in multiple levels of Inheritances.
# Python program showing
# how MRO works
class A:
def rk(self):
print(" In class A")
class B(A):
def rk(self):
print(" In class B")
class C(A):
def rk(self):
print("In class C")
# classes ordering
class D(B, C):
pass
r = D()
r.rk()

3. Write a python code to read a phone number and email-id from the user and validate
it for correctness.
# Python program to extract emails From
# the String By Regular Expression.
# Importing module required for regular
# expressions
import re
# Example string
s = """Hello from [email protected]
to [email protected] about the meeting @2PM"""
# \S matches any non-whitespace character
# @ for as in the Email
# + for Repeats a character one or more times
lst = re.findall('\S+@\S+', s)
# Printing of List
print(lst)
Week- 7:
1. Write a Python code to merge two given file contents into a third file.
# Python program to
# demonstrate merging
# of two files
data = data2 = ""
# Reading data from file1
with open('file1.txt') as fp:
data = fp.read()
# Reading data from file2
with open('file2.txt') as fp:
data2 = fp.read()
# Merging 2 files
# To add the data of file2
# from next line
data += "\n"
data += data2
with open ('file3.txt', 'w') as fp:
fp.write(data)
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. \

# Python3 program to check if a sentence

# can be formed from a given set of words.

#include <bits/stdc++.h>

ALPHABET_SIZE = 26;

# here isEnd is an integer that will store

# count of words ending at that node

class trieNode:

def init (self):

self.t = [None for i in range(ALPHABET_SIZE)]

self.isEnd = 0

# utility function to create a new node

def getNode():

temp = trieNode()
return temp;
# Function to insert new words in trie
def insert(root, key):
trail = None
trail = root;
# Iterate for the length of a word
for i in range(len(key)):
temp = None
# If the next key does not contains the character
if (trail.t[ord(key[i]) - ord('a')] == None):
temp = getNode();
trail.t[ord(key[i]) - ord('a')] = temp;
trail = trail.t[ord(key[i]) - ord('a')];
# isEnd is increment so not only
# the word but its count is also stored
(trail.isEnd) += 1
# Search function to find a word of a sentence
def search_mod(root, word):
trail = root;
# Iterate for the complete length of the word
for i in range(len(word)):
# If the character is not present then word
# is also not present
if (trail.t[ord(word[i]) - ord('a')] == None):
return False;
# If present move to next character in Trie
trail = trail.t[ord(word[i]) - ord('a')];
# If word found then decrement count of the word
if ((trail.isEnd) > 0 and trail != None):
# if the word is found decrement isEnd showing one
# occurrence of this word is already taken so
(trail.isEnd) -= 1
return True;
else:
return False;
# Function to check if string can be
# formed from the sentence
def checkPossibility(sentence, m, root):
flag = 1;
# Iterate for all words in the string
for i in range(m):
if (search_mod(root, sentence[i]) == False):
# if a word is not found in a string then the
# sentence cannot be made from this dictionary of words
print('NO', end='')
return;
# If possible
print('YES')
# Function to insert all the words of dict in the Trie
def insertToTrie(dictionary, n, root):
for i in range(n):
insert(root, dictionary[i]);
# Driver Code
if name ==' main ':
root = getNode();
# Dictionary of words
dictionary = [ "find", "a", "geeks",
"all", "for", "on",
"geeks", "answers", "inter" ]
N = len(dictionary)
# Calling Function to insert words of dictionary to tree
insertToTrie(dictionary, N, root);
Write a Python code to Read text from a text file, find the word
with most number of occurrences
# String to be checked
sentence = [ "find", "all", "answers", "on",
"geeks", "for", "geeks" ]
M = len(sentence)
# Function call to check possibility
checkPossibility(sentence, M, root);
# This code is contributed by pratham76
Output:
YES

3. Write a Python code to Read text from a text file, find the word with most number
of occurrences
def find_most_frequent_word(filename):
try:
with open(filename, 'r') as file:
text = file.read()
# Remove punctuation and convert to lowercase
for char in "-.,\n":
text = text.replace(char, " ")
text = text.lower()
words = text.split()
word_count = {}
# Count occurrences of each word
for word in words:
word_count[word] = word_count.get(word, 0) + 1
# Find the word with the most occurrences
most_frequent = max(word_count, key=word_count.get)
count = word_count[most_frequent]
print(f"The most frequent word is: '{most_frequent}' (occurs {count} times)")
except FileNotFoundError:
print("File not found. Please check the file name or path.")
# Example usage
filename = "sample.txt" # Replace with your file path
find_most_frequent_word(filename)

Input (file: sample.txt):


Python is easy to learn. Python is powerful. Python is popular.
Output:
The most frequent word is: 'python' (occurs 3 times)

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.

# Python3 code to demonstrate working of


# Most frequent word in Strings List
# Using loop + max() + split() + defaultdict()
from collections import defaultdict
# initializing Matrix
test_list = ["gfg is best for geeks", "geeks love gfg", "gfg is best"]
# printing original list
print("The original list is : " + str(test_list))
temp = defaultdict(int)
# memoizing count
for sub in test_list:
for wrd in sub.split():
temp[wrd] += 1
# getting max frequency
res = max(temp, key=temp.get)
# printing result
print("Word with maximum frequency : " + str(res))
Output
The original list is : ['gfg is best for geeks', 'geeks love gfg', 'gfg is best']
Word with maximum frequency : gfg
Import numpy, Plotpy and Scipy and explore their functionalities
# Python3 Program to count vowels,
# consonant, digits and special
# character in a given string.
# Function to count number of vowels,
# consonant, digits and special
# character in a string.
def countCharacterType(str):
# Declare the variable vowels,
# consonant, digit and special
# characters
vowels = 0
consonant = 0
specialChar = 0
digit = 0
# str.length() function to count
# number of character in given string.
for i in range(0, len(str)):
ch = str[i]
if ( (ch >= 'a' and ch <= 'z') or
(ch >= 'A' and ch <= 'Z') ):
# To handle upper case letters
ch = ch.lower()
if (ch == 'a' or ch == 'e' or ch == 'i'
or ch == 'o' or ch == 'u'):
vowels += 1
else:
consonant += 1
elif (ch >= '0' and ch <= '9'):
digit += 1
else:
specialChar += 1
print("Vowels:", vowels)
print("Consonant:", consonant)
print("Digit:", digit)
print("Special Character:", specialChar)
# Driver function.
str = "geeks for geeks121"
countCharacterType(str)
# This code is contributed by
# Smitha Dinesh Semwal
Output:
Vowels: 5
Consonant: 8
Digit: 3
Special Character: 2

Week - 8:
1. Import Numpy, Plotpy and Scipy and explore their functionalities.
# Importing required libraries
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
# -------- NumPy Functionalities --------
print("----- NumPy Functionalities -----")
array = np.array([1, 2, 3, 4, 5])
print("Array:", array)
mean = np.mean(array)
print("Mean of array:", mean)
matrix = np.array([[1, 2], [3, 4]])
print("Matrix:\n", matrix)
print("Transpose:\n", matrix.T)
# -------- Matplotlib (Plotpy) Functionalities --------
print("\n----- Matplotlib (Plotpy) Functionalities -----")
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y, label="sin(x)")
plt.title("Sine Wave")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.legend()
plt.grid(True)
plt.show()
# -------- SciPy Functionalities --------
print("\n----- SciPy Functionalities -----")
data = [1, 2, 2, 3, 4, 4, 4, 5]
mode = stats.mode(data)
print("Mode of data:", mode.mode[0], "with frequency:", mode.count[0])
Explanation of Functionalities:
NumPy: Handles arrays, linear algebra, and statistical operations.
Matplotlib (Plotpy): Used for plotting graphs like line, bar, scatter, etc.
SciPy: Builds on NumPy; includes stats, optimization, integration, etc.
Output Summary:
Printed array, mean, matrix transpose (NumPy)
Displayed a sine graph (Matplotlib)
Calculated mode using statistics (SciPy)
2. Install NumPy package with pip and explore it.
# using the iris dataset
df = px.data.iris()
# plotting the bubble chart
fig = px.scatter(df, x="species", y="petal_width",
size="petal_length", color="species")
# showing the plot
fig.show()
Output:

Installation
Plotly does not come built-in with Python. To install it type the below command in the
terminal.
pip install plotly
This may take some time as it will install the dependencies as well.
Package Structure of Plotly
There are three main modules in Plotly. They are:
• plotly.plotly
• plotly.graph.objects
• plotly.tools
plotly.plotly acts as the interface between the local machine and Plotly. It contains functions
that require a response from Plotly’s server.
plotly.graph_objects module contains the objects (Figure, layout, data, and the definition
of
the plots like scatter plot, line chart) that are responsible for creating the plots. The Figure
can
be represented either as dict or instances of plotly.graph_objects.Figure and these are
serialized as JSON before it gets passed to plotly.js. Consider the below example for better
understanding.
Note: plotly.express module can create the entire Figure at once. It uses the graph_objects
internally and returns the graph_objects.Figure instance.
Example:
How to Install Numpy on Windows?
• Last Updated : 09 Sep, 2021
1 Read
2 Discuss
Python NumPy is a general-purpose array processing package that provides tools for
handling n-dimensional arrays. It provides various computing tools such as comprehensive
mathematical functions, linear algebra routines. NumPy provides both the flexibility of
Python and the speed of well-optimized compiled C code. Its easy-to-use syntax makes it
highly accessible and productive for programmers from any background.
Pre-requisites:
The only thing that you need for installing Numpy on Windows are:
• Python
• PIP or Conda (depending upon user preference)

Installing Numpy on Windows:


For Conda Users:
If you want the installation to be done through conda, you can use the below command:
conda install -c anaconda numpy
You will get a similar message once the installation is complete

Make sure you follow the best practices for installation using conda as:
• Use an environment for installation rather than in the base environment using the below
command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
For PIP Users:
Users who prefer to use pip can use the below command to install NumPy:
pip install numpy
You will get a similar message once the installation is complete:

Now that we have installed Numpy successfully in our system, let’s take a look at few simple
examples.
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
# Python3 program to illustrate
# working of Not gate
def XNOR(a,b):
if(a == b):
return 1
else:
return 0
# Driver code
if __name__=='__main ':
print(XNOR(1,1))
print("+ + +")
print(" | XNOR Truth Table | Result |")
print(" A = False, B = False | A XNOR B =",XNOR(False,False)," | ")
print(" A = False, B = True | A XNOR B =",XNOR(False,True)," | ")
print(" A = True, B = False | A XNOR B =",XNOR(True,False)," | ")
print(" A = True, B = True | A XNOR B =",XNOR(True,True)," | ")
Output:

1
+ + +
| XNOR Truth Table | Result |
A = False, B = False | A XNOR B = 1 |
A = False, B = True | A XNOR B = 0 |
A = True, B = False | A XNOR B = 0 |
A = True, B = True | A XNOR B = 1 |
# Python3 program to illustrate
# working of NOR gate

def NOR(a, b):


if(a == 0) and (b == 0):
return 1
elif(a == 0) and (b == 1):
return 0
elif(a == 1) and (b == 0):
return 0
elif(a == 1) and (b == 1):
return 0

# Driver code
if __name__=='__main ':
print(NOR(0, 0))

print("+ + +")
print(" | NOR Truth Table | Result |")
print(" A = False, B = False | A NOR B =",NOR(False,False)," | ")
print(" A = False, B = True | A NOR B =",NOR(False,True)," | ")
print(" A = True, B = False | A NOR B =",NOR(True,False)," | ")
print(" A = True, B = True | A NOR B =",NOR(True,True)," | ")
Output:
1
+ + +
| NOR Truth Table | Result |
A = False, B = False | A NOR B = 1 |
A = False, B = True | A NOR B = 0 |
A = True, B = False | A NOR B = 0 |
A = True, B = True | A NOR B = 0 |

4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
# Function to print sum and carry
def getResult(A, B):
# Calculating value of sum
Sum = A ^ B
# Calculating value of Carry
Carry = A & B
# printing the values
print("Sum ", Sum)
print("Carry", Carry)
# Driver code
A=0
B=1
# passing two inputs of halfadder as arguments to get result function
getResult(A, B)
Output:
Sum 1
Carry 0
5. Write a GUI program to create a window wizard having two text labels, two text
fields and two buttons as Submit and Reset.
# Import Module
from tkinter import *
# create root window
root = Tk()
# root window title and dimension
root.title("Welcome to GeekForGeeks")
# Set geometry (widthxheight)
root.geometry('350x200')
# all widgets will be here
# Execute Tkinter
root.mainloop()

You might also like