0% found this document useful (0 votes)
7 views

PYTHON PROGRAMMING LAB ASSIGNMENTS Final (1)

The document outlines the Python Programming Lab Assignments for the BCAAE301 course at the University of Engineering and Management for the period of June 2024 to December 2024. It includes course objectives, outcomes, and a series of assignments divided into modules covering topics such as control flow, iterators, functions, and data structures like strings, lists, dictionaries, and tuples. Each assignment provides specific tasks aimed at enhancing students' understanding and application of Python programming concepts.

Uploaded by

deepikadalvi18
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

PYTHON PROGRAMMING LAB ASSIGNMENTS Final (1)

The document outlines the Python Programming Lab Assignments for the BCAAE301 course at the University of Engineering and Management for the period of June 2024 to December 2024. It includes course objectives, outcomes, and a series of assignments divided into modules covering topics such as control flow, iterators, functions, and data structures like strings, lists, dictionaries, and tuples. Each assignment provides specific tasks aimed at enhancing students' understanding and application of Python programming concepts.

Uploaded by

deepikadalvi18
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

University of Engineering and Management

Institute of Engineering & Management, Salt Lake Campus Institute of Engineering


& Management, New Town Campus University of Engineering & Management, Jaipur

PYTHON PROGRAMMING LAB ASSIGNMENTS


BCAAE301
June 2024-December 2024

IEM, BCA and M.Sc. Information Science Department


University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

COURSE OBJECTIVES:

Throughout the course, students will be expected to demonstrate their understanding of Python
Programming by being able to do each of the following:

1. To apply fundamental concepts of Python Programming for problem solving

2. To understand the fundamentals different data types, operators and conditional operators
in python.

3. To understand and apply and work with string, list, tuple and dictionary.

4. To apply logical reasoning to design programs using object oriented programing and use
python modules and packages.

COURSE OUTCOMES:

CO1: Understand the importance and basic concepts of Python Programming and be able to apply
them in problem solving

CO2: To understand basic concepts of flow control statements and concept of iterators and able to
apply flow control statements to solve problems

CO3: To get familiarize and understand basic set and dictionary operations and be able to apply the
concept for solving real word problems

CO4: Understand some basic properties of object oriented programming in python, and be able to
analyze practical examples.
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

MODULE 1: Introduction to Python Programming

NO OF LABS REQUIRED: 3HRS, 1 WEEK

LIST OF ASSIGNMENTS:

Question 1 You can use the Python interpreter as a calculator. Demonstrate the same
for the following tasks:
a. 2+4
b. 2*4
c. 2^4
d. 2/4

Solution

Question 2 Demonstrate the use of Python to represent a complex number. Calculate


the conjugate of an input complex number. Print the real, imaginary and
magnitude separately for the conjugate number.
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

Question 3 Create a list of animals that are kept as pets and call this list pets.
a. Print the first element of the list.
b. Print all the values in the list except the first element.
Solution

Question 4 Write a Python program to take two integers as input and perform the
following arithmetic operations:
a. Add
b. Subtract
c. Multiply
d. Division
Solution inp = input(‘Input value of variable 1:’)
a = int(inp)
inp = input(‘Input value of variable 2:’)
b = int(inp)
# Addition
c = a+b
print(c)
# Subtraction
c = a-b
print(c)
# Multiplication
c = a*b
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

print(c)
# Division
c = a/b
print(c)
Question 5 Create a dictionary containing the key-value pairs:
a. A: Apple
b. B: Baby
c. C: Cat
d. D: Dog
Print the value at key position C.
Solution

Question 6 Create a set of characters from an input string in Python.


Solution

Question 7 a. Create a set with values (1,2,3) in Python. Add the value 4 to this set.
b. Using the update() method, update the set with values (5,6,7,8).
Solution

Question 8 Demonstrate the use of import statement in Python.


a. Import the math library and print the value of π.
b. Import the string library and print all the recognized digits within the
library.
Solution
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

Question 9 Calculate the factorial of a user-input value x using math library.


Solution import math
inp = input(‘Input x:’)
x = int(inp)
ans = math.factorial(x)
print(ans)
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

MODULE 2: Control Flow , Iterators and Functions

NO OF LABS REQUIRED: 4 HRS ; 2 WEEKS

LIST OF ASSIGNMENTS:

Question 1 1 . Any integer is input through the keyboard. Write a program to find out
whether it is an odd number or even number.

Solution x = int(input('Enter any number: '))


j=2
if x % j == 0 :
print('Even Number')
else :
print('Odd Nu
Question 2 Any year is input through the keyboard. Write a program to determine
whether the year is a leap year or not.
year = int(input('Enter a year: '))
if year % 4 == 0 :
if year % 100 == 0 :
if year % 400 == 0 :
print(year, 'is a Leap Year')
else :
print(year, 'is not a Leap Year')
else :
print(year, 'is a Leap Year')
else :
print(year, 'is not a Leap Year)
Question 3 Find the maximum and minimum of three numbers
Solution num1 = int(input('Enter First Number: '))
num2 = int(input('Enter Second Number: '))
num3 = int(input('Enter Third Number: '))
if num1 > num2 :
max = num1
else :
max = num2
if max < num3
max = num3
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

print (“\n The maximum of three numbers is = “ , max);

Question 4 Given the length and breadth of a rectangle, write a program to find
whether the area of the rectangle is greater than its perimeter. For
example, the area of the rectangle with length = 5 and breadth = 4 is
greater than its perimeter.
Solution length = int(input('Enter length of rectangle: '))
breadth = int(input('Enter breadth of rectangle: '))
area = length * breadth
perimeter = 2 * (length + breadth)
print('Area =', area, 'Perimeter =', perimeter)
if area > perimeter :
print('Area of Rectangle is greater than perimeter')
else :
print('Perimeter of Rectangle is greater than area')
Question 5 Write a program to print first 25 odd numbers using range( ).
Solution j=1
print(‘First 25 Odd Numbers:’)
for I in range(50) :
if I % j == 1 :
print(I, end = ‘, ‘)
I += 1
Question 6 Write a program to find all the numbers between 0 to 500 which are
divisible by 3 and 5
Solution for I in range (0,500):
x=I
If x%3 == 0 and x%5 == 0 :
print(i)
Question 7 Find the GCD of two numbers (with and without Functions)
Solution num1 = 36
num2 = 60
gcd = 1

for I in range(1, min(num1, num2)):


if num1 % I == 0 and num2 % I == 0:
gcd = i
print(“GCD of”, num1, “and”, num2, “is”, gcd)

def gcd(a, b):

# Everything divides 0
if (a == 0):
return b
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

if (b == 0):
return a

# base case
if (a == b):
return a

# a is greater
if (a > b):
return gcd(a-b, b)
return gcd(a, b-a)
Question 8 Check whether a number is Armstrong number or not.
Condition for Armstrong number: if the sum of each of its digits when
raised to the power of 3 is equal to itself. 153 = 1^3 +5^3 + 3^3 = 1 + 125 +
27 = 153
Solution n = int(input(‘Enter any number: ‘))

s=n
b = len(str(n))
sum1 = 0
while n != 0:
r = n % 10
sum1 = sum1+(r**b)
n = n//10
if s == sum1:
print(“The given number”, s, “is Armstrong number”)
else:
print(“The given number”, s, “is not Armstrong number”)

def isArmstrong(x):

n = order(x)
temp = x
sum1 = 0

while (temp != 0):


r = temp % 10
sum1 = sum1 + power(r, n)
temp = temp // 10

# If condition satisfies
return (sum1 == x)

Question 9 Check whether a number is prime or not. (With and without function)
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

Solution num = int(input(‘Enter any number: ‘))


if num > 1:
for i in range(2, (num//2)+1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

import math

def is_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
Question 10 Generate first 10 numbers in a Fibonacci Series
(With and Without Function)
Solution n = 10
num1 = 0
num2 = 1
next_number = num2
count = 1

while count <= n:


print(next_number, end=” “)
count += 1
num1, num2 = num2, next_number
next_number = num1 + num2
print()

def Fibonacci(n):

# Check if input is 0 then it will


# print incorrect input
if n < 0:
print("Incorrect input")

# Check if n is 0
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

# then it will return 0


elif n == 0:
return 0

# Check if n is 1,2
# it will return 1
elif n == 1 or n == 2:
return 1

else:
return Fibonacci(n-1) + Fibonacci(n-2)

Question 11 Factorial of Number (With or without function)


Solution n=int(input("Enter number:"))
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of the number is: ")
print(fact)
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

MODULE 3: Strings, List, Dictionaries, Tuples

NO OF LABS REQUIRED: 4 HRS ; 2 WEEKS

LIST OF ASSIGNMENTS:
Use the given two lists for questions 1 to 9.

world_animals=['Anaconda', 'Platypus','Red panda', 'Beaver', 'Killer whale', 'Platypus', 'Camel', 'Polar


bear', 'King penguin', 'Snow leopard', 'Zebra', 'Plains bison']

world_biomes=['Tropical Rainforest','Temperate Forest','Taiga', 'Marine','Freshwater',


'Desert','Arctic Tundra','AntarticaTundra','Alpine Tundra', 'Tropical Grassland' ,' Temperate Grassland
']

1. Create a program to calculate and return the length of the given two
lists.

Answer >>> world_animals=['Anaconda', 'Platypus','Red panda', 'Beaver', 'Killer


whale', 'Platypus', 'Camel', 'Polar bear', 'King penguin', 'Snow leopard',
'Zebra', 'Plains bison']
>>> print("The length of the list world_animals is ",len(world_animals))
The length of the list world_animals is 12
>>>
>>>
>>> world_biomes=['Tropical Rainforest','Temperate Forest','Taiga',
'Marine','Freshwater', 'Desert','Arctic Tundra','AntarticaTundra','Alpine
Tundra', 'Tropical Grassland' ,' Temperate Grassland ']
>>>
>>> print("The length of the list world_biomes is ",len(world_biomes))
The length of the list world_biomes is 11
>>>
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

2. Create a program to count up how many times an item appears in a


given list.
Given:
 Platypus in world_animals
 Taiga in world_biomes

Answer >>> world_animals=['Anaconda', 'Platypus','Red panda', 'Beaver', 'Killer


whale', 'Platypus', 'Camel', 'Polar bear', 'King penguin', 'Snow leopard',
'Zebra', 'Plains bison']
>>>
>>> world_biomes=['Tropical Rainforest','Temperate Forest','Taiga',
'Marine','Freshwater', 'Desert','Arctic Tundra','AntarticaTundra','Alpine
Tundra', 'Tropical Grassland' ,' Temperate Grassland ']
>>>
>>> print("Platypus occurence in the list of
world_animals",world_animals.count("Platypus"))
Platypus occurence in the list of world_animals 2

>>> print("Taiga occurence in the list of


world_biomes",world_biomes.count("Taiga"))
Taiga occurence in the list of world_biomes 1

3. Write a program to find the index of the first matching element for
 'Snow leopard' in the list of world_animals.

Answer >>> world_animals=['Anaconda', 'Platypus','Red panda', 'Beaver', 'Killer


whale', 'Platypus', 'Camel', 'Polar bear', 'King penguin', 'Snow leopard',
'Zebra', 'Plains bison']

>>> print("The animal Snow leopard is in the


index",world_animals.index("Snow leopard"))
The animal Snow leopard is in the index 9
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

4. Write a program to examine a list for an item.


 Anaconda in world_animals
 Forest in world_biomes

Answer >>> world_animals=['Anaconda', 'Platypus','Red panda', 'Beaver', 'Killer


whale', 'Platypus', 'Camel', 'Polar bear', 'King penguin', 'Snow leopard',
'Zebra', 'Plains bison']
>>>
>>> world_biomes=['Tropical Rainforest','Temperate Forest','Taiga',
'Marine','Freshwater', 'Desert','Arctic Tundra','AntarticaTundra','Alpine
Tundra', 'Tropical Grassland' ,' Temperate Grassland ']
>>>
if "Anaconda" in world_animals:
print("List 'world_animals' contains element Anaconda.")
else:
print("List 'world_animals' does not contain element Anaconda.")

if "Forest" in world_biomes:
print("List 'world_biomes' contains element Forest.")
else:
print("List 'world_biomes' does not contain element Forest.")

C:/Users/INDU/AppData/Local/Programs/Python/Python310/list08feb/
prgexer/Listingprg4.py
List 'world_animals' contains element Anaconda.
List 'world_biomes' does not contain element Forest.

5. Write a program to reverse the order of the world_biomes list in


Python
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

Answer >>>
>>> world_biomes=['Tropical Rainforest','Temperate Forest','Taiga',
'Marine','Freshwater', 'Desert','Arctic Tundra','AntarticaTundra','Alpine
Tundra', 'Tropical Grassland' ,' Temperate Grassland ']
>>>
>>> print('\nOriginal List = ', world_biomes)
Original List = ['Tropical Rainforest', 'Temperate Forest', 'Taiga', 'Marine',
'Freshwater', 'Desert', 'Arctic Tundra', 'AntarticaTundra', 'Alpine Tundra',
'Tropical Grassland', ' Temperate Grassland ']
>>>
>>> world_biomes.reverse()
>>> print('\nReverse List = ', world_biomes)

Reverse List = [' Temperate Grassland ', 'Tropical Grassland', 'Alpine


Tundra', 'AntarticaTundra', 'Arctic Tundra', 'Desert', 'Freshwater', 'Marine',
'Taiga', 'Temperate Forest', 'Tropical Rainforest']
>>>

6. Write a python script that concatenates the above given two lists into
one.

Answer >>> world_animals=['Anaconda', 'Red panda', 'Beaver', 'Killer whale',


'Platypus', 'Camel', 'Polar bear', 'King penguin', 'Snow leopard', 'Zebra',
'Plains bison']
>>>
>>> world_biomes=['Tropical Rainforest','Temperate Forest','Taiga',
'Marine','Freshwater', 'Desert','Arctic Tundra','AntarticaTundra','Alpine
Tundra', 'Tropical Grassland' ,' Temperate Grassland ']
>>>
>>> print("Concatenating two lists")
Concatenating two lists
>>>
>>> print(world_animals+world_biomes)
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

['Anaconda', 'Red panda', 'Beaver', 'Killer whale', 'Platypus', 'Camel', 'Polar


bear', 'King penguin', 'Snow leopard', 'Zebra', 'Plains bison', 'Tropical
Rainforest', 'Temperate Forest', 'Taiga', 'Marine', 'Freshwater', 'Desert',
'Arctic Tundra', 'AntarticaTundra', 'Alpine Tundra', 'Tropical Grassland', '
Temperate Grassland ']

7. Write a program to insert world_animals list at a given position.


Given:
Item is ,”Elephant”
Position is 3

Answer >>> world_animals=['Anaconda', 'Red panda', 'Beaver', 'Killer whale',


'Platypus', 'Camel', 'Polar bear', 'King penguin', 'Snow leopard', 'Zebra',
'Plains bison']
>>> world_animals.insert(3,"Elephant")
>>> print(world_animals)
['Anaconda', 'Red panda', 'Beaver', 'Elephant', 'Killer whale', 'Platypus',
'Camel', 'Polar bear', 'King penguin', 'Snow leopard', 'Zebra', 'Plains bison']

8. Create your own multiline string and show how to print it.

Answer >>> # Creating a multiline string


>>> multiline_str = """I'm learning Introduction to Strings in Python.
... Its quite interesting to implement all the problem excerises .
... It gives the complete knowledge to all Python programmers."""
>>> print("Multiline string: \n" + multiline_str)
Multiline string:
I'm learning Introduction to Strings in Python.
Its quite interesting to implement all the problem excerises .
It gives the complete knowledge to all Python programmers.
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

9. Create a program that accepts a string and displays each word's length
and the length of the string.
(Exercise1.py)

Answer #Exercise1.py
def splitString (str):
# split the string by spaces
str = str.split (' ')
# iterate words in string
for words in str:
print (words,":""(",len(words),")")

# Main code
# declare string and assign value
str = "Self control will place (a man) among the Gods;"
print("Length of the string",len(str))
# call the function
splitString(str)

C:\Users\User> python > Exercise1.py


Length of the string 47
Self :( 4 )
control :( 7 )
will :( 4 )
place :( 5 )
(a :( 2 )
man) :( 4 )
among :( 5 )
the :( 3 )
Gods; :( 5 )

>>> def splitString (str):


... for words in str.split():
... print(words, ":", "(", len(words), ")")
...
>>> string = "Self control will place (a man) among the Gods;"
>>> print(“Length of the string”, len(string))
>>> splitString(string)
Self : ( 4 )
control : ( 7 )
will : ( 4 )
place : ( 5 )
(a : ( 2 )
man) : ( 4 )
among : ( 5 )
the : ( 3 )
Gods; : ( 5 )
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

10. Write a program that will count the number of lowercase and
uppercase character in a user-supplied string.
(Exercise2.py)

def countUpperAndLowerCase(sentence):
upper = 0
lower = 0
for i in sentence:
if i >='A' and i <= 'Z':
upper += 1
elif i >= 'a' and i <= 'z':
lower += 1
print("Upper case: " + str(upper))
print("Lower case: " + str(lower))

countUpperAndLowerCase("Introduction to Strings in Python")

C:\Users\User> python > Exercise2.py


Upper case: 3
Lower case: 26

Answer >>> def countUpperAndLowerCase(sentence):


... upper = 0
... lower = 0
... for i in sentence:
... if i >='A' and i <= 'Z':
... upper += 1
... elif i >= 'a' and i <= 'z':
... lower += 1
... print("Upper case: " + str(upper))
... print("Lower case: " + str(lower))
...
>>> countUpperAndLowerCase("Introduction to Strings in Python")

Upper case: 3
Lower case: 26

11. Create a program that will count the length of the given string without
relying on an in-built function.
Given string:
“Jack and Jill went up the hill. To fetch a pail of water. “

Answer >>> str1 = "Jack and Jill went up the hill. To fetch a pail of water."
>>> print("The string is :")
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

The string is :
>>> print(str1)
Jack and Jill went up the hill. To fetch a pail of water.
>>> counter=0
>>> for i in str1:
... counter=counter+1
...
>>> print("The length of the string is ", counter)
The length of the string is 57

12. Write a program to elicit a string from the user and then determine the
total number of characters included in a string.
(Exercise3.py)

# Python Program to Count Total Characters in a String


str1 = input("Please Enter your Own String : ")
total = 0
for i in str1:
total = total + 1
print("Total Number of Characters in this String = ", total)

C:\Users\User> python > Exercise3.py


Please Enter your Own String : hope
Total Number of Characters in this String = 4

Answer >>> str1 = input("Please Enter your Own String : ")


Please Enter your Own String : hope
>>> total = 0
>>> for i in str1:
... total = total + 1
...
>>> print("Total Number of Characters in this String = ", total)
Total Number of Characters in this String = 4

13. Write a program to elicit a string from the user in lower or small case
letters and then Capitalize the initial character of the string.

Answer >>> str1 = input ("Please enter the required lowercase string that needs to
be capitalised. : ")
Please enter the required lowercase string that needs to be capitalised. :
print('Input string: ', str1)
>>> x = str1.capitalize()
>>> print('Capitalised input string: ', x)
Capitalised input string: Print('input string: ', str1)
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

14. Write a program that obtains a user-supplied string. Use the


isnumeric() to determine whether or not it contains numbers.

Answer >>> string= input("User, enter the string to check if it is all numbers : ")
User, enter the string to check if it is all numbers : 123
>>> if string.isnumeric():
... print("The string is numeric.")
... else:
... print("The string is not numeric.")
...
The string is numeric.
>>> string= input("User, enter the string to check if it is all numbers : ")
User, enter the string to check if it is all numbers : tes
>>> if string.isnumeric():
... print("The string is numeric.")
... else:
... print("The string is not numeric.")
...
The string is not numeric.

15. Write a program that obtains a user-supplied string . Use the isdigits()
to determine whether or not it contains digits.

Answer >>> string = input("User, enter the string to check if it is all digits : ")
User, enter the string to check if it is all digits : 123
>>> if string.isdigit():
... print("The string is digits.")
... else:
... print("The string is not digits.")
...
The string is digits.
>>> string = input("User, enter the string to check if it is all digits : ")
User, enter the string to check if it is all digits : test
>>> if string.isdigit():
... print("The string is digits.")
... else:
... print("The string is not digits.")
...
The string is not digits.
>>>

16. The longest word in dictionary is


Pneumonoultramicroscopicsilicovolcanoconiosis.
Write a program that takes the longest given word in dictionary, as an
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

input and output the count of only the distinct characters in it.
(Exercise4.py)

Answer def count_distinct_chars(string):


count = 0 #Intialise count
# examine each letter in the string, iteratively.
for ch in string:
# check for the presence of the character in the string
if string.find(ch) == string.rfind(ch):
count += 1
return count # Return the number of distinct characters
print(count_distinct_chars("Pneumonoultramicroscopicsilicovolcanoconios
is"))

C:\Users\User> python > Exercise4.py


3
5
5

Answer >>> def count_distinct_chars(string):


... count = 0 #Intialise count
... # examine each letter in the string, iteratively.
... for ch in string:
... # check for the presence of the character in the string
... if string.find(ch) == string.rfind(ch):
... count += 1
... return count # Return the number of distinct characters
...
>>>
print(count_distinct_chars("Pneumonoultramicroscopicsilicovolcanoconios
is"))
5

17. Given:
“string1=Pneumonoultramicroscopicsilicovolcanoconiosis.”
Write a Python program that, takes the given string, and returns a new
string with all the vowels stripped out.

Answer >>> string1="Pneumonoultramicroscopicsilicovolcanoconiosis"


>>>
>>> vowels = "aeiouAEIOU"
>>> new_string = ""
>>> for chr in string1:
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

... if chr not in vowels:


... new_string+= chr
...
>>>
>>> print(new_string)
Pnmnltrmcrscpcslcvlcncnss

18. Construct a dictionary of pulses and their calorie counts from the table
below. Write a program that accesses the matching value at the key.

Pulses Calories
Chickpeas 164
Lentils 116
Black beans 127
Pinto beans 115
Kidney beans 112
Peas 81

Answer >>> pulses_calories={'Chickpeas':164, 'Lentils': 116, 'Black beans': 127,


'Pinto beans': 115, 'Kidney beans': 112, 'Peas': 81}
>>> d = pulses_calories
>>> d
{'Chickpeas': 164, 'Lentils': 116, 'Black beans': 127, 'Pinto beans': 115,
'Kidney beans': 112, 'Peas': 81}

>>> print("Access Key at 'Chickpeas' location: ", d['Chickpeas']) # access


value at key ' Chickpeas'
Access Key at 'Chickpeas' location: 164
>>> print("Access Key at 'Lentils' location: ", d['Lentils']) # access value
at key 'Lentils.'
Access Key at 'Lentils' location: 116
>>> print("Access Key at 'Pinto beans' location: ", d['Pinto beans']) #
access value at key ' Pinto beans'
Access Key at 'Pinto beans' location: 115
>>> print("Access Key at 'Peas' location: ", d['Peas']) # access value at key
'Peas'
Access Key at 'Peas' location: 81

19. Write a Python script to create and print a dictionary (x, x*x)
containing a number (between 1 and n) in the form (x, x).

Answer >>> n=int(input("Input a number "))


University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

Input a number 8
>>> d=dict()
>>> for x in range(1,n+1):
... d[x]=x*x
...
>>> print(d)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

20. Find the highest three values of matching dictionary keys using the
Python program.
my_dict = {'Ether': 233, 'Bitcoin': 4854, 'Litecoin': 789, 'Gaslimit':
13325}

Answer >>> from collections import Counter


>>> # Initial Dictionary
>>> my_dict = {'Ether': 233, 'Bitcoin': 4854, 'Litecoin': 789, 'Gaslimit':
13325}
>>> k = Counter(my_dict)
>>> # Finding 3 highest values
>>> high = k.most_common(3)
>>>
>>> print("Dictionary with 3 highest values:")
Dictionary with 3 highest values:
>>> print("Keys: Values")
Keys: Values
>>> for i in high:
... print(i[0]," :",i[1]," ")
...
Gaslimit : 13325
Bitcoin : 4854
Litecoin : 789
>>>

21. Make a replica of the sample dictionary with the dict() function:
sampledict = {
"brand": "HP",
"model": "Pavilion",
"year": 2022
}

Answer >>> sampledict = {


... "brand": "HP",
... "model": "Pavilion",
... "year": 2022
... }
>>> dict1 = dict(sampledict)
>>> print("The original dictionary:")
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

The original dictionary:


>>> print(dict1)
{'brand': 'HP', 'model': 'Pavilion', 'year': 2022}

>>> dict2=dict(dict1)
>>> print("The replicated dictionary using dict():")
The replicated dictionary using dict():
>>> print(dict2)
{'brand': 'HP', 'model': 'Pavilion', 'year': 2022}
>>>

22. By writing a Python program, check if two sets have no elements in


common.

Answer >>> x = {"Ether","Bitcoin","Litecoin"}


>>> y = {"Bitcoin","Gas"}
>>> z = {"Ganache"}
>>> print("Original set elements:")
Original set elements:
>>> x
{'Ether', 'Bitcoin', 'Litecoin'}
>>> y
{'Gas', 'Bitcoin'}
>>> z
{'Ganache'}
>>> print("Confirm two given sets have no element(s) in common:")
Confirm two given sets have no element(s) in common:
>>> print("Compare x and y: " , x.isdisjoint(y))
Compare x and y: False
>>> print("Compare x and z: " , x.isdisjoint(z))
Compare x and z: True
>>> print("Compare y and z: " , y.isdisjoint(z))
Compare y and z: True
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

MODULE 4: Modules, Packages, Object Oriented


Programming

NO OF LABS REQUIRED: 4 HRS ; 2 WEEKS

LIST OF ASSIGNMENTS:
1. Write a Python program to generate a random color hex, a random alphabetical
string, random value between two integers (inclusive) and a random multiple of
7 between 0 and 70. Use random.randint()
Answer import random
: import string
print("Generate a random color hex:")
print("#{:06x}".format(random.randint(0, 0xFFFFFF)))
print("\nGenerate a random alphabetical string:")
max_length = 255
s = ""
for i in range(random.randint(1, max_length)):
s += random.choice(string.ascii_letters)
print(s)
print("Generate a random value between two integers, inclusive:")
print(random.randint(0, 10))
print(random.randint(-7, 7))
print(random.randint(1, 1))
print("Generate a random multiple of 7 between 0 and 70:")
print(random.randint(0, 10) * 7)
2. Write a Python program to select a random element from a list, set, dictionary-
value, and file from a directory. Use random.choice()
Answer import random
: import os
print("Select a random element from a list:")
elements = [1, 2, 3, 4, 5]
print(random.choice(elements))
print(random.choice(elements))
print(random.choice(elements))
print("\nSelect a random element from a set:")
elements = set([1, 2, 3, 4, 5])
# convert to tuple because sets are invalid inputs
print(random.choice(tuple(elements)))
print(random.choice(tuple(elements)))
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

print(random.choice(tuple(elements)))
print("\nSelect a random value from a dictionary:")
d = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
key = random.choice(list(d))
print(d[key])
key = random.choice(list(d))
print(d[key])
key = random.choice(list(d))
print(d[key])
print("\nSelect a random file from a directory.:")
print(random.choice(os.listdir("/")))
3. Write a Python program to construct a seeded random number generator, also
generate a float between 0 and 1, excluding 1. Use random.random()
Answer import random
print("Construct a seeded random number generator:")
print(random.Random().random())
print(random.Random(0).random())
print("\nGenerate a float between 0 and 1, excluding 1:")
print(random.random())
4. Write a Python program to shuffle the elements of a given list. Use
random.shuffle()
Answer import random
nums = [1, 2, 3, 4, 5]
print("Original list:")
print(nums)
random.shuffle(nums)
print("Shuffle list:")
print(nums)
words = ['red', 'black', 'green', 'blue']
print("\nOriginal list:")
print(words)
random.shuffle(words)
print("Shuffle list:")
print(words)
5. Write a Python program to check if a function is a user-defined function or not.
Use types.FunctionType, types.LambdaType()
Answer import types
def func():
return 1

print(isinstance(func, types.FunctionType))
print(isinstance(func, types.LambdaType))
print(isinstance(lambda x: x, types.FunctionType))
print(isinstance(lambda x: x, types.LambdaType))
print(isinstance(max, types.FunctionType))
print(isinstance(max, types.LambdaType))
print(isinstance(abs, types.FunctionType))
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

print(isinstance(abs, types.LambdaType))
6. Write a Python program to construct a Decimal from a float and a Decimal from
a string. Also represent the decimal value as a tuple. Use decimal.Decimal
Answer import decimal
: print("Construct a Decimal from a float:")
pi_val = decimal.Decimal(3.14159)
print(pi_val)
print(pi_val.as_tuple())
print("\nConstruct a Decimal from a string:")
num_str = decimal.Decimal("123.25")
print(num_str)
print(num_str.as_tuple())
7. Write a Python program to configure rounding to round up and round down a
given decimal value. Use decimal.Decimal
Answer import decimal
: print("Configure the rounding to round up:")
decimal.getcontext().prec = 1
decimal.getcontext().rounding = decimal.ROUND_UP
print(decimal.Decimal(30) / decimal.Decimal(4))
print("\nConfigure the rounding to round down:")
decimal.getcontext().prec = 3
decimal.getcontext().rounding = decimal.ROUND_DOWN
print(decimal.Decimal(30) / decimal.Decimal(4))
print("\nConfigure the rounding to round up:")
print(decimal.Decimal('8.325').quantize(decimal.Decimal('.01'),
rounding=decimal.ROUND_UP))
print("\nConfigure the rounding to round down:")
print(decimal.Decimal('8.325').quantize(decimal.Decimal('.01'),
rounding=decimal.ROUND_DOWN))
8. Write a Python program to configure the rounding to round to the floor, ceiling.
Use decimal.ROUND_FLOOR, decimal.ROUND_CEILING
Answer import decimal
: print("Configure the rounding to round to the floor:")
decimal.getcontext().prec = 4
decimal.getcontext().rounding = decimal.ROUND_FLOOR
print(decimal.Decimal(20) / decimal.Decimal(6))
print("\nConfigure the rounding to round to the ceiling:")
decimal.getcontext().prec = 4
decimal.getcontext().rounding = decimal.ROUND_CEILING
print(decimal.Decimal(20) / decimal.Decimal(6))
9. Write a Python program to create a shallow copy of a given list. Use copy.copy
Answer import copy
:
nums_x = [1, [2, 3, 4]]
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

print("Original list: ", nums_x)

nums_y = copy.copy(nums_x)

print("\nCopy of the said list:")

print(nums_y)

print("\nChange the value of an element of the original list:")

nums_x[1][1] = 10

print(nums_x)

print("\nSecond list:")

print(nums_y)

nums = [[1], [2]]

nums_copy = copy.copy(nums)

print("\nOriginal list:")

print(nums)

print("\nCopy of the said list:")

print(nums_copy)

print("\nChange the value of an element of the original list:")

nums[0][0] = 0

print("\nFirst list:")

print(nums)

print("\nSecond list:")

print(nums_copy)

10. Write a Python program to create a shallow copy of a given dictionary. Use
copy.copy
Answer import copy
: nums_x = {"a":1, "b":2, 'cc':{"c":3}}
print("Original dictionary: ", nums_x)
nums_y = copy.copy(nums_x)
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

print("\nCopy of the said list:")


print(nums_y)
print("\nChange the value of an element of the original dictionary:")
nums_x["cc"]["c"] = 10
print(nums_x)
print("\nSecond dictionary:")
print(nums_y)

nums = {"x":1, "y":2, 'zz':{"z":3}}


nums_copy = copy.copy(nums)
print("\nOriginal dictionary :")
print(nums)
print("\nCopy of the said list:")
print(nums_copy)
print("\nChange the value of an element of the original dictionary:")
nums["zz"]["z"] = 10
print("\nFirst dictionary:")
print(nums)
print("\nSecond dictionary (copy):")
print(nums_copy)
11. Write a Python program to get the name of the operating system (Platform
independent), information of the current operating system, current working
directory, print files and directories in the current directory, and raise errors if
the path or file name is invalid.
12. Write a Python program to check access to a specified path. Test the existence,
readability, writability and executability of the specified path.
13. Write a Python program to retrieve the current working directory and change the
dir (move up one).
14 Write a Python program to join one or more path components together and split
a given path into directories and files.
15 Write a Python program to get information about the file pertaining to file
mode. Print the information - ID of device containing file, inode number,
protection, number of hard links, user ID of owner, group ID of owner, total size
(in bytes), time of last access, time of last modification and time of last status
change.
16 Write a Python program to convert degrees to radians.
Note : The radian is the standard unit of angular measure, used in many areas
of mathematics. An angle's measurement in radians is numerically equal to the
length of a corresponding arc of a unit circle; one radian is just under 57.3
degrees (when the arc length is equal to the radius).
Test Data:
Degree : 15
Expected Result in radians: 0.2619047619047619
17 Write a Python program to calculate the area of a parallelogram.
Note : A parallelogram is a quadrilateral with opposite sides parallel (and
therefore opposite angles equal). A quadrilateral with equal sides is called a
rhombus, and a parallelogram whose angles are all right angles is called a
University of Engineering and Management
Institute of Engineering & Management, Salt Lake Campus Institute of Engineering
& Management, New Town Campus University of Engineering & Management, Jaipur

rectangle.
Test Data:
Length of base : 5
Height of parallelogram : 6
Expected Output: Area is : 30.0
18 Write a Python program to calculate the surface volume and area of a cylinder.
Note: A cylinder is one of the most basic curvilinear geometric shapes, the
surface formed by the points at a fixed distance from a given straight line, the
axis of the cylinder.
Test Data:
volume : Height (4), Radius(6)
Expected Output:
Volume is : 452.57142857142856
Surface Area is : 377.1428571428571
19 Get Index of the list by attributes.
20 Shuffle a deck of card with OOPS in Python

21 Write a Python program to create a person class. Include attributes like name,
country and date of birth. Implement a method to determine the person’s age.
22 Write a Python program to create a class representing a bank. Include methods
for managing customer accounts and transactions.
23 Write a Python program to create a class representing a shopping cart. Include
methods for adding and removing items, and calculating the total price.
24 Write a Python program to create a calculator class. Include methods for basic
arithmetic operations.

You might also like