PYTHON PROGRAMMING LAB ASSIGNMENTS Final (1)
PYTHON PROGRAMMING LAB ASSIGNMENTS Final (1)
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:
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
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 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 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
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.
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
# 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
# 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
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
def Fibonacci(n):
# 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
# 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)
LIST OF ASSIGNMENTS:
Use the given two lists for questions 1 to 9.
1. Create a program to calculate and return the length of the given two
lists.
3. Write a program to find the index of the first matching element for
'Snow leopard' in the list of world_animals.
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.
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)
6. Write a python script that concatenates the above given two lists into
one.
8. Create your own multiline string and show how to print it.
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)
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))
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)
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
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.
>>>
input and output the count of only the distinct characters in it.
(Exercise4.py)
17. Given:
“string1=Pneumonoultramicroscopicsilicovolcanoconiosis.”
Write a Python program that, takes the given string, and returns a new
string with all the vowels stripped out.
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
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).
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}
21. Make a replica of the sample dictionary with the dict() function:
sampledict = {
"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}
>>>
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
nums_y = copy.copy(nums_x)
print(nums_y)
nums_x[1][1] = 10
print(nums_x)
print("\nSecond list:")
print(nums_y)
nums_copy = copy.copy(nums)
print("\nOriginal list:")
print(nums)
print(nums_copy)
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
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.