Python Programming
Python Programming
Python Programming
Vision:
To be a world-class educational and research institution in the service of humanity by promoting high
quality education in Engineering, Management and Pharmacy
Mission:
M1: Develop the faculty to reach the international standards.
M2: Maintain high academic standards and teaching quality that promotes the analytical thinking and
independent judgment.
M3: Promote research, innovation and product development by collaboration with reputed foreign
Universities.
M4: Offer collaborative industry program in emerging areas and spirit of enterprise.
M5: Improve employability potential through soft skills and technical skills
III. GOALS
To evolve as an autonomous (Deemed University) institution offering viable programmes of relevance
for the upliftment of rural students and populace.
To undertake Nationally and Internationally acknowledged Research and Development works in all
disciplines by forging alliances with research organizations, government entities, industries and alumni.
GNITC has taken strategic steps to ensure a gradual enhancement of all infrastructural facilities to
make the campus even more advanced to simply put it; it will soon resemble a foreign university on
this side of the globe.
To achieve the status as provider of Quality Education and Excellent Research Center on par with IISCs
and IITs.
0 1 22
Course Objectives:
To install and run the Python interpreter
To learn control structures.
To Understand Lists, Dictionaries in python
To Handle Strings and Files in Python
Course Outcomes: After completion of the course, the student should be able to
● Develop the application specific codes using python.
● Understand Strings, Lists, Tuples and Dictionaries in Python
● Verify programs using modular approach, file I/O, Python standard library
● 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.
Week 2:
3. i)Write a program to calculate compound interest when principal, rate and number of periods aregiven.
ii)Given coordinates (x1, y1), (x2, y2) find the distance between two points
4. Read name, address, email and phone number of a person through keyboard and print the details.
Week - 3:
5. Print the below triangle using for loop.
5
44
333
2222
11111
6. 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)
Week 4:
7. Python Program to Print the Fibonacci sequence using while loop
8. Python program to print all prime numbers in a given interval (use break)
Week 5:
9. i) Write a program to convert a list and tuple into arrays.
ii) Write a program to find common values between two arrays.
Week - 6:
10. Write a function called gcd that takes parameters a and b and returns their greatest common divisor.
11.Write a function called palindrome that takes a string argument and returns True if it is a palindrome
and False otherwise. Remember that you can use the built-in function len to check the length of a string.
Week 7:
12. 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.
13. 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.
Week 8:
14. 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?
15. Writes a recursive function that generates all binary strings of n-bit length
Week 9:
16. 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
Week 10:
17. How do you make a module? Give an example of construction of a module using different
geometricalshapes and operations on them as its functions.
18. Use the structure of exception handling all general purpose exceptions.
Week 11:
19. 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.
20. Write a Python program to demonstrate the usage of Method Resolution Order (MRO) in multiple
levels of Inheritances.
21. Write a python code to read a phone number and email-id from the user and validate it for
correctness.
Week 12:
22. Write a Python code to merge two given file contents into a third file.
23. Write a Python code to open a given file and construct a function to check for given words present
init and display on found.
24. Write a Python code to Read text from a text file, find the word with most number of occurrences
25. 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.
Downloaded by Sundari YBT ([email protected])
lOMoARcPSD|20682595
Week 13:
26. Import numpy, Plotpy and Scipy and explore their functionalities.
27. a) Install NumPy package with pip and explore it.
28. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
Week 14:
29. Write a program to implement Half Adder, Full Adder, and Parallel Adder
30. Write a GUI program to create a window wizard having two text labels, two text fields and two
buttonsas Submit and Reset.
TEXT BOOKS:
REFERENCE BOOKS:
Week 1:
1-i) Use a web Browser to go to the python website http://python.org. This page contain
information about python and links to python related pages, and it gives you the ability to
search the python documentation.
Sol:
Step 2: Here We will see different types of links and click on Documentation
Step 3: After click on documentation it opens the documentation web page. Here we will see different types of links like
tutorial, library references, etc..
Step 4: Here we will see details about installation procedure of python modules
Step 5:In this tutorial module it gives all the details about python.
Step 6:In this tutorial module it gives all the details about python.
ii)Start the Python interpreter and type help() to start the online help utility.
Description:
Python help()
help(object)
help() Parameters
object (optional) - you want to generate the help of the given object
The help() method is used for interactive use. It's recommended to try it in your interpreter when you
>>> help(list)
>>> help(dict)
>>> help(print)
If string is passed as an argument, the given string is looked up as the name of a module, function, class,
>>> help('print')
>>> help('def')
help('math.pow')
If no argument is passed, Python's help utility (interactive help system) starts on the console.
>>> help()
Then, you can enter the name of the topic to get help on writing Python programs and using Python
help> True
help> 'print'
To quit the help utility and return to the interpreter, you need to type quit and press enter.
Description:
Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>>. (It
shouldn’t take long.)
Numbers:
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value.
Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages
(for example, Pascal or C); parentheses ( ()) can be used for grouping. For example:
>>> 2+2
4
>>> 50-5*6
20
>>> (50-5*6)/4
5.0
>>> 8/5 # division always returns a floating point number
1.6
The integer numbers (e.g. 2, 4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) have
type float. We will see more about numeric types later in the tutorial.
Division (/) always returns a float. To do floor division and get an integer result you can use
the // operator; to calculate the remainder you can use %:
The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the
next interactive prompt:
>>> width=20
>>> height=5*9
>>> width*height
900
Week 2:
3.i)Write a program to calculate compound interest when principal, rate and number of periods are
given.
Aim:To write a program to calculate compound interest when principal, rate and number of periods
are given.
Description:
Let us discuss the formula for compound interest. The formula to calculate compound interest annually
is given by:
A = P(1 + R/100) t
Compound Interest = A – P
Where,
A is amount
P is the principal amount
R is the rate and
t is the time span
Program:
#Taking input from user.
principal = int(input("Enter the principal amount: "))
rate = int(input("Enter rate of interest: "))
time = int(input("Enter time in years: " ))
#calculating compound interest
Amount = principal * (pow((1 + rate / 100), time))
CI = Amount - principal
print("Compound interest is", CI)
Output:
Enter the principal amount: 5000
Enter rate of interest: 10
Enter time in years: 2
Compound interest is 1050.000000000001
3.ii)Given coordinates (x1, y1), (x2, y2) find the distance between two points
Aim:To given coordinates (x1, y1), (x2, y2) find the distance between two points
Description:
Distance =
We can get above formula by simply applying Pythagoras theorem
Program:
#Taking input from the user
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
#calculating distance
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)
OutPut:
enter x1 : 10
enter x2 : 4
enter y1 : 9
enter y2 : 1
distance between (10, 4) and (9, 1) is : 10.0
4.Read name, address, email and phone number of a person through keyboard and
print the details.
Aim: To read name, address, email and phone number of a person through keyboard and print the
details.
Program:
# read name, address, email and phone number from user and print them
name = input("Enter your name:")
address = input("Enter your address:")
email = input("Enter your email:")
phoneno= input("Enter your phone number:")
print("Name: ", name)
print("Contact: ", address)
print("Email: ", email)
print("Birthday: ", phoneno)
Output:
Enter your name:usha
Enter your address:vijawada
Enter your email:[email protected]
Enter your phone number:9876543210
Name: usha
Contact: vijawada
Email: [email protected]
Birthday: 9876543210
Week 3:
Program:
rows = int(input("Enter the number of rows: "))
# Outer loop will print number of rows
for i in range(rows):
# Inner loop will print the value of i after each iteration
for j in range(i):
print(rows-i, end=" ") # print number
# line after each row to display pattern correctly
print(" ")
Output:
Enter the number of rows: 6
5
4 4
3 3 3
2 2 2 2
1 1 1 1 1
6. 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)
Aim: To 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)
Description:
Given a character, the task is to check whether the given character is in upper case, lower case, digit,
and special character
Examples:
Input: ch = 'A' Output: A is an Upper Case character
Input: ch = 'a' Output: a is an Lower Case character
Input: ch = '0' Output: 0 is a digit
Input: ch = '$' Output: $ is an Special character
The elif statement: The elif statement enables us to check multiple conditions and execute
the specific block of statements depending upon the true condition among them. We can have
any number of elif statements in our program depending upon our need. However, using elif is
optional.
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
The syntax of the elif statement is given below.
1. if expression 1:
2. # block of statements
3. elif expression 2:
4. # block of statements
5. elif expression 3:
6. # block of statements
7. else:
8. # block of statements
Program:
ch=input("Enter character: ")
if (ch >= 'A' and ch <= 'Z'):
print(ch,"is an UpperCase character");
elif (ch >= 'a' and ch <= 'z'):
print(ch,"is an LowerCase character");
elif (ch >= '0' and ch <= '9'):
print(ch,"is a digit");
else:
print(ch,"is a special character");
Output 1:
Enter character: B
B is an UpperCase character
Output 2:
Enter character: b
b is an LowerCase character
Output 3:
Enter character: 6
6 is a digit
Output 4:
Enter character: $
$ is a special character
Downloaded by Sundari YBT ([email protected])
lOMoARcPSD|20682595
Week 4:
7. Python Program to Print the Fibonacci sequence using while loop
Aim:To Print the Fibonacci sequence using while loop
Description:
Fibonacci sequence specifies a series of numbers where the next number is found by adding
up the two numbers just before it.
In mathematical terms, the sequence "Fn" of the Fibonacci sequence of numbers is defined by
the recurrence relation:
Fn= Fn_1+ Fn_2
Where seed values are:
F0=0 and F1=1
While Loop
The Python while loop iteration of a code block is executed as long as the given condition, i.e.,
conditional_expression, is true.
If we don't know how many times we'll execute the iteration ahead of time, we can write an
indefinite loop.
1. while conditional_expression:
2. # block of statements
Program:
Output:
8.Python program to print all prime numbers in a given interval (use break)
The user is given two integer numbers, lower value, and upper value. The task is to write the
Python program for printing all the prime numbers between the given interval (or range).
To print all the prime numbers between the given interval, the user has to follow the following
steps:
Program:
# First, we will take the input:
lower_value = int(input ("Please, Enter the Lowest Range Value: "))
upper_value = int(input ("Please, Enter the Upper Range Value: "))
Output:
Please, Enter the Lowest Range Value: 5
Please, Enter the Upper Range Value: 30
Downloaded by Sundari YBT ([email protected])
lOMoARcPSD|20682595
Week 5:
9 .i)Write a program to convert a list and tuple into arrays.
Aim:To write a program to convert a list and tuple into arrays
Description:
List: A list is of an ordered collection data type that is mutable which means it can be easily modified
and we can change its data values and a list can be indexed, sliced, and changed and each element can be
accessed using its index value in the list. The following are the main characteristics of a List:
The list is an ordered collection of data types.
The list is mutable.
List are dynamic and can contain objects of different data types.
List elements can be accessed by index number.
Array: An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together. This makes it easier to calculate the position of each element
by simply adding an offset to a base value, i.e., the memory location of the first element of the array
(generally denoted by the name of the array). The following are the main characteristics of an Array:
An array is an ordered collection of the similar data types.
An array is mutable.
An array can be accessed by using its index number.
Tuple: A tuple is an ordered and an immutable data type which means we cannot change its values
and tuples are written in round brackets. We can access tuple by referring to the index number inside
the square brackets. The following are the main characteristics of a Tuple:
Tuples are immutable and can store any type of data type.
it is defined using ().
it cannot be changed or replaced as it is an immutable data type.
Program:
import numpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print("Before converting list \n ",my_list)
list_to_array=np.asarray(my_list)
print("After converting List to array: \n",list_to_array)
my_tuple = ([8, 4, 6], [1, 2, 3])
print("Before converting Tuple \n",my_tuple)
tuple_to_array=np.asarray(my_tuple)
print("After converting Tuple to array: \n",tuple_to_array)
Output:
Before converting list
[1, 2, 3, 4, 5, 6, 7, 8]
After converting List to array:
Downloaded by Sundari YBT ([email protected])
lOMoARcPSD|20682595
[1 2 3 4 5 6 7 8]
Before converting Tuple
([8, 4, 6], [1, 2, 3])
After converting Tuple to array:
[[8 4 6]
[1 2 3]]
Output:
Array1: [ 0 10 20 40 60]
Array2: [10, 30, 40]
Common values between two arrays:
[10 40]
Week 6:
10.Write a function called GCD that takes parameters a and b and returns their greatest common
divisor.
Aim: To write a function called GCD that takes parameters a and b and returns their greatest common
divisor.
Description:
In Python, the math module contains a number of mathematical operations, which can be performed
with ease using the module. math.gcd() function compute the greatest common divisor of 2 numbers
mentioned in its arguments.
Syntax: math.gcd(x, y)
Program:
# Python code to demonstrate the working of gcd()
# importing "math" for mathematical operations
import math
a = int(input("Enter the a value: "))
b = int(input("Enter b value:" ))
if(math.gcd(a, b)):
print('Greatest Common Divisor of', a, 'and', b, 'is', math.gcd(a, b))
else:
print('not found')
Output:
Enter the a value: 24
Enter b value:36
Greatest Common Divisor of 24 and 36 is 12
11.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.
Aim: To 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.
Description:
Given a string, write a python function to check if it is palindrome or not. A string is said to be a
palindrome if the reverse of the string is the same as the string. For example, “radar” is a palindrome,
but “radix” is not a palindrome.
Examples:
Input : malayalam Output : Yes
Input : geeks Output : No
Method :
1. Find reverse of the string
2. Check if reverse and original are same or not.
Iterative Method: Run a loop from starting to length/2 and check the first character to the last
character of the string and second to second last one and so on …. If any character mismatches,
the string wouldn’t be a palindrome.
Program:
# 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 = input("Enter the string ")
ans = isPalindrome(s)
if (ans):
print("The given string is palindrome")
else:
print("the given string is not a palindrome")
Output:
Enter the string malayalam
The given string is palindrome
Downloaded by Sundari YBT ([email protected])
lOMoARcPSD|20682595
Week 7:
12.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.
Aim: To 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.
Description:
Using sort() The new list can be made as a copy of the original list, sorting the new list and
comparing with the old list will give us the result if sorting was required to get sorted list or not.
Program:
# function to check list is sorted or not
def is_sorted(list):
# using sort() to
# check sorted list
test_list1 = list[:]
test_list1.sort()
if (test_list1 == list):
return ‘True’
else:
return ‘False’
# main function
# initializing list
input_string = input("Enter a list element separated by space ")
test_list = input_string.split()
Print(is_sorted(test_list))
Output 1:
Enter a list element separated by space 2 0 1 3 5
False
Output 2:
Enter a list element separated by space 1 2 3 4 5
True
13.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.
Aim: To 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.
Description:
1. we have sorted the given list using the built-in sort() method which will place the duplicate values
corresponding to each other if exist.
2. Then we run first for loop to store the index value and second loop to compare the corresponding
values.
3. In the first iteration, the value of i is 1 and the inner loop will be executed (0, 1) times.
4. The value of list[i] is 1 and the value of list[i-1] is 1.
5. Hence there are duplicated elements so we have returned the 'true'.
Program:
#function to check list has duplicates or not
def has_duplicates(list1):
list1.sort()
for i in range(1, len(list1)):
for j in range(0, i):
if list1[i] == list1[i-1]:
return 'True'
return 'False'
# main function
# initializing list
input_string = input("Enter a list element separated by space ")
test_list= input_string.split()
print(has_duplicates(test_list))
Output 1:
Enter a list element separated by space 1 2 1 2 3
True
Output 2:
Enter a list element separated by space 1 2 3 4 5
False
13. 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.
Aim: To 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.
Description:
We need to take a list, with duplicate elements in it and generate another list that only contains
the element without the duplicates in them.
Examples:
Input : [2, 4, 10, 20, 5, 2, 20, 4]
Output : [2, 4, 10, 20, 5]
Program:
# Python code to remove duplicate elements
def Remove(duplicate):
final_list = []
for num in duplicate:
if num not in final_list:
final_list.append(num)
return final_list
# main function
duplicate = [2, 4, 10, 20, 5, 2, 20, 4]
print("Original List: ",duplicate)
print("After removing duplicates list is: ",Remove(duplicate))
Output:
Original List: [2, 4, 10, 20, 5, 2, 20, 4]
After removing duplicates list is: [2, 4, 10, 20, 5]
OutPut:
Aim: To 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.
Description:
Dictionary is quite a useful data structure in programming that is usually used to hash a particular
key with value so that they can be retrieved efficiently. Let’s discuss various ways of swapping the
keys and values in Python Dictionary.
Example:
Input :
{'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69}
Output: {67: 'A', 69: 'F', 23: 'B', 56: 'D', 12: 'E', 45: 'C'}
Program:
# Python3 code to demonstrate
# swap of key and value
# initializing dictionary
old_dict = {'A': 67, 'B': 23, 'C': 45, 'E': 12, 'F': 69, 'G': 67, 'H': 23}
# Printing original dictionary
print ("Original dictionary is : ")
print(old_dict)
print()
new_dict = {}
for key, value in old_dict.items():
if value in new_dict:
new_dict[value].append(key)
else:
new_dict[value]=[key]
# Printing new dictionary after swapping
# keys and values
print ("Dictionary after swapping is : ")
print("keys: values")
for i in new_dict:
Output:
Original dictionary is :
{'A': 67, 'B': 23, 'C': 45, 'E': 12, 'F': 69, 'G': 67, 'H': 23}
Week 8:
14. i)Add a comma between the characters. If the given word is 'Apple', it should
become 'A,p,p,l,e'
Aim: To add a comma between the characters. If the given word is 'Apple', it should become
'A,p,p,l,e'
Program:
# Python3 code to demonstrate working of
# Adding comma between characters
word = "Apple"
new_word = ' '
print("original Word: ",word)
for i in word:
new_word = ','.join(word)
print("Word after separated with comma: ",new_word)
OutPut:
Program:
print("Enter the String: ")
text = input()
print("Enter a Word to Delete: ")
word = input()
text = text.replace(word, "")
print()
print(text)
Output:
Enter the String:
python language is high level programming language
Enter a Word to Delete:
language
python is high level programming
14.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?
Aim: To 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?
Description:
programs to read a file and capitalize the first letter of every word in the file and print it as output.
To capitalize the first letter we will use different methods using Python. The Python String Method
is used to convert the first character in each word to Uppercase and the remaining characters to
Lowercase in the string and return the new string.
Input: hello world
Output: Hello World
Program:
# Python program to capitalize the
# first character of each word in a sentence
# Function definition
def solve (st):
ascii_array = []
# creating a list of ascii values
# of all the characters in the sentence
for i in range (0, len (st)):
ascii_array.append (ord (st[i]))
# check if the first character of
# each word is a lowercase character.
# To convert a lowercase character to an
# uppercase character, we subtract 32 from
# the ASCII value of lowercase character.
if ascii_array[0] >= 97 and ascii_array[0] <= 122 :
ascii_array[0] = ascii_array[0] - 32
Output:
Enter the String: python programming
Python Programming
15.Writes a recursive function that generates all binary strings of n-bit length
Aim: To writes a recursive function that generates all binary strings of n-bit length
Description:
Given a positive integer number N. The task is to generate all the binary strings of N bits. These
binary strings should be in ascending order.
Program:
# 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 = int(input("Enter the number of bits:"))
arr = [None] * n
# Print all binary strings
generateAllBinaryStrings(n, arr, 0)
Output:
Enter the number of bits:2
0 0
0 1
1 0
1 1
Week 9:
16.i)Write a python program that defines a matrix and prints
Aim: To write a python program that defines a matrix and prints
Description:
Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a
rectangular array of data or numbers. The horizontal entries in a matrix are called as ‘rows’
while the vertical entries are called as ‘columns’. If a matrix has r number of rows and c
number of columns then the order of matrix is given by r x c. Each entries in a matrix can be
integer values, or floating values, or even it can be complex numbers.
Examples:
// 3 x 4 matrix
1234
M= 4567
6789
// 2 x 3 matrix in Python
A = ( [ 2, 5, 7 ],
[ 4, 7, 9 ] )
Program:
# 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 row wise:")
# 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 row wise:
1
2
3
4
5
6
1 2 3
4 5 6
Output:
Resultant Matrix:
[2, 4, 6]
[8, 10, 12]
[14, 16, 18]
Y = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] * Y[i][j]
print("Resultant Matrix: ")
for r in result:
print®
Output:
Resultant Matrix:
[1, 4, 9]
[16, 25, 36]
[49, 64, 81]
Week 10:
17.How do you make a module? Give an example of construction of a module using
different geometricalshapes and operations on them as its functions.
Aim:
Program:
Description:
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Program:
# Python program to demonstrate exception handling structure
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output:
Can't divide by zero
This is always executed