You are on page 1of 41

lOMoARcPSD|20682595

Python Programming

Python Programming (Jawaharlal Nehru Technological University, Hyderabad)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)
lOMoARcPSD|20682595

GURU NANAK INSTITUTIONS TECHNICAL CAMPUS


(AUTONOMOUS)
SCHOOL OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING (CYBER SECURITY)

Python Programming Lab Manual


(22ES0CS10)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

I. VISION & MISSION

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

II. QUALITY POLICY


GNITC is committed to provide quality education through dedicated and talented faculty, world class
infrastructure, labs and updated research center to the students.

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.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

PYTHON PROGRAMMING LABORATORY

B.Tech. I Year II Sem. L T P C

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.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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 (sundari.ybt@hmgi.ac.in)
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:

1. Supercharged Python: Take your code to the next level, Overland


2. Learning Python, Mark Lutz, O'reilly

REFERENCE BOOKS:

1. Python Programming: A Modern Approach, Vamsi Kurama, Pearson


2. Python Programming A Modular Approach with Graphics, Database, Mobile, and Web
Applications, Sheetal Taneja, Naveen Kumar, Pearson
3. Programming with Python, A User’s Book, Michael Dawson, Cengage Learning, India Edition
4. Think Python, Allen Downey, Green Tea Press
5. Core Python Programming, W. Chun, Pearson
6. Introduction to Python, Kenneth A. Lambert, Cengage

Week 1:

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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 1:Goto Browser and enter http://python.org.

Step 2: Here We will see different types of links and click on Documentation

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Step 6:In this tutorial module it gives all the details about python.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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

Description:

Python help()

The help() method calls the built-in Python help system.

The syntax of help() is:

help(object)

help() Parameters

The help() method takes a maximum of one parameter.

 object (optional) - you want to generate the help of the given object

How help() works in Python?

The help() method is used for interactive use. It's recommended to try it in your interpreter when you

need help to write Python program and use Python modules.

Note: object is passed to help() (not a string)

Try these on Python shell.

>>> help(list)

>>> help(dict)

>>> help(print)

>>> help([1, 2, 3])

If string is passed as an argument, name of a module, function, class, method, keyword, or

documentation topic, and a help page is printed.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Note: string is passed as an argument to help()

If string is passed as an argument, the given string is looked up as the name of a module, function, class,

method, keyword, or documentation topic, and a help page is printed.

Try these on Python shell.

>>> help('random thing')

>>> help('print')

>>> help('def')

>>> from math import *

help('math.pow')

Note: no argument is passed to help()

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

modules. For example:

help> True

help> 'print'

help > print

To quit the help utility and return to the interpreter, you need to type quit and press enter.

help > quit

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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

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 %:

>>> 17/3 # classic division returns a float


5.666666666666667
>>> 17//3 # floor division discards the fractional part
5
>>> 17%3 # the % operator returns the remainder of the division
2
>>> 5*3+2 # floored quotient * divisor + remainder
17

With Python, it is possible to use the ** operator to calculate powers 1:

>>> 5**2 # 5 squared


25
>>> 2**7 # 2 to the power of 7
128

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

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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:

Calculate the distance between two points.


We will use the distance formula derived from Pythagorean theorem. The formula for distance between
two point (x1, y1) and (x2, y2) is

Distance =
We can get above formula by simply applying Pythagoras theorem

calculate distance between two points

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

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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:usha@gmail.com
Enter your phone number:9876543210
Name: usha
Contact: vijawada
Email: usha@gmail.com
Birthday: 9876543210

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Week 3:

5. Print the below triangle using for loop.


5
44
333
2222
11111

Aim: To print the below triangle using for loop.

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

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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 (sundari.ybt@hmgi.ac.in)
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.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, … and so on.

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.

Syntax of Python While Loop

1. while conditional_expression:
2. # block of statements

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Program:

Number = int(input("\n Please Enter the Range : "))


# Initializing First and Second Values
i = 0
First_Value = 0
Second_Value = 1
# Find & Displaying
print(“Fibonoccie Series: ”)
while(i < Number):
print(First_Value)
Next = First_Value + Second_Value
First_Value = Second_Value
Second_Value = Next
i = i + 1

Output:

Please Enter the Range : 10


Fibonoccie Series:
0
1
1
2
3
5
8
13
21
34

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

8.Python program to print all prime numbers in a given interval (use break)

Aim:To print all prime numbers in a given interval (use break)


Description:
A prime number is a natural number which is greater than 1 and has no positive divisor other
than 1 and itself, such as 2, 3, 5, 7, 11, 13, and so on.

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:

o Step 1: Loop through all the elements in the given range.


o Step 2: Check for each number if it has any factor between 1 and itself.
o Step 3: If yes, then the number is not prime, and it will move to the next number.
o Step 4: If no, it is the prime number, and the program will print it and check for the next
number.
o Step 5: The loop will break when it is reached to the upper value.

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: "))

print ("The Prime Numbers in the range are: ")


for number in range (lower_value, upper_value + 1):
# prime numbers are greater than 1
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:
print (number)

Output:
Please, Enter the Lowest Range Value: 5
Please, Enter the Upper Range Value: 30
Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)
lOMoARcPSD|20682595

The Prime Numbers in the range are:


5
7
11
13
17
19
23
29

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


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 (sundari.ybt@hmgi.ac.in)
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]]

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

Aim: To write a program to find common values between two arrays.


Program:
import numpy as np
array1 = np.array([0, 10, 20, 40, 60])
print("Array1: ",array1)
array2 = [10, 30, 40]
print("Array2: ",array2)
print("Common values between two arrays:")
print(np.intersect1d(array1, array2))

Output:
Array1: [ 0 10 20 40 60]
Array2: [10, 30, 40]
Common values between two arrays:
[10 40]

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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 (sundari.ybt@hmgi.ac.in)
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

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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]

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

13.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.
Aim: To The wordlist I provided, words.txt, doesn’t contain single letter words. So you
might want to add “I”, “a”, and the empty string.
Program:

OutPut:

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

13.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.

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:

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

print(i, " :", new_dict[i])

Output:
Original dictionary is :
{'A': 67, 'B': 23, 'C': 45, 'E': 12, 'F': 69, 'G': 67, 'H': 23}

Dictionary after swapping is :


keys: values
67 : ['A', 'G']
23 : ['B', 'H']
45 : ['C']
12 : ['E']
69 : ['F']

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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:

original Word: Apple


Word after separated with comma: A,p,p,l,e

14.ii)Remove the given word in all the places in a string


Aim:To remove the given word in all the places in a string

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

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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

# create an empty list which will store


# the characters corresponding to the
# ascii values in ascii_array
newlist = []
newlist.append (chr (ascii_array[0]))
for i in range (1, len (ascii_array)):

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

# 32 is the ascii value for 'space' or ' '.


# so we use this condition to check for
# the next word in the sentence
# as in a sentence we have space separated words
if ascii_array[i] == 32:
if ascii_array[i + 1] >= 97 and ascii_array[i+1] <= 122:
ascii_array[i + 1] = ascii_array[i+1] - 32
newlist.append (chr (ascii_array[i]))

# in the end, we return a string after


# joining the values obtained in newlist
return (''.join (newlist))
# Driver Code
string = input("Enter the String: ")
result = solve (string)
print (result)

Output:
Enter the String: python programming
Python Programming

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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()

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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

16.ii)Write a python program to perform addition of two square matrices


Aim:To write a python program to perform addition of two square matrices
Program:
# Program to add two matrices using nested loop
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
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(r)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Output:
Resultant Matrix:
[2, 4, 6]
[8, 10, 12]
[14, 16, 18]

16.iii)Write a python program to perform multiplication of two square matrices


Aim: To write a python program to perform multiplication of two square matrices
Program:
# Program to add two matrices using nested loop
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]

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]

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

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:

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

18.Use the structure of exception handling all general purpose exceptions.


Aim:To use the structure of exception handling all general purpose exceptions.

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

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)

You might also like