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

Domain Fundamentals_Assignments_Python

The document outlines a series of programming assignments that require users to write various Python programs. These programs cover topics such as accepting user input, performing calculations, checking conditions, and manipulating arrays. Each assignment includes a description of the task, the expected input and output, and the code implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Domain Fundamentals_Assignments_Python

The document outlines a series of programming assignments that require users to write various Python programs. These programs cover topics such as accepting user input, performing calculations, checking conditions, and manipulating arrays. Each assignment includes a description of the task, the expected input and output, and the code implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Assignments

1. Accept a char input from the user and display it on the console.

Code of the program & screenshot of the output.


n=input("enter your name\n")
print("your name is "+n)

2. Accept two inputs from the user and output its sum.

Variable Data Type

Number 1 Integer
Number 2 Float

Sum Float

Code of the program & screenshot of the output.


n=int(input("enter 2 numbers"))
w=float(input())
sum=n+w
print("sum is "+str(sum))

3. Write a program to find the simple interest.


a. Program should accept 3 inputs from the user and calculate simple interest for
the given inputs. Formula: SI=(P*R*n)/100)

Variable Data Type

Principal amount (P) Integer

Interest rate (R) Float

Number of years (n) Float

Simple Interest (SI) Float

Code of the program & screenshot of the output.


p=int(input("enter principle amount"))
r=float(input("enter rate of intrest"))
n=float(input("enter number of years "))

SI=((p*r*n)/100)
print("simple interest is : "+str(SI))
4. Write a program to check whether a student has passed or failed in a subject after he or
she enters their mark (pass mark for a subject is 50 out of 100).
a. Program should accept an input from the user and output a message as
“Passed” or “Failed”

Variable Data type

mark float

Code of the program & screenshot of the output.


m=int(input("enter your mark"))

if(m<50):
print("you have failed")
5. Write a program to show the grade obtained by a student after he/she enters their total
mark percentage.
a. Program should accept an input from the user and display their grade as
follows

Mark Grade

> 90 A

80-89 B

70-79 C

60-69 D

50-59 E

< 50 Failed

Variable Data type

Total mark float


Code of the program & screenshot of the output.
m=int(input("enter your mark"))
if m>=90:
print("your grade is A")
elif m>=80:
print("your grade is B")
elif m>=70:
print("your grade is C")
elif m>=60:
print("your grade is D")
elif m>=50:
print("your grade is E")
else :
print("your have failed")

6. Using the ‘switch case’ write a program to accept an input number from the user and
output the day as follows.
Input Output

1 Sunday

2 Monday

3 Tuesday

4 Wednesday

5 Thursday

6 Friday

7 Saturday

Any other input Invalid Entry

Code of the program & screenshot of the output.


n=int(input("enter a number between 1-7 \n"))
def switch(m):
if m==1:
print("sunday")
elif m==2:
print("monday")
elif m==3:
print("tuesday")
elif m==4:
print("wednesday")
elif m==5:
print("thursday")
elif m==6:
print("friday")
elif m==7:
print("Saturday")
else :
print("wrong choice")

switch(n)

7. Write a program to print the multiplication table of given numbers. Using for and while
a. Accept an input from the user and display its multiplication table

Eg:

Output: Enter a number

Input: 5

Output:

1x5=5

2 x 5 = 10
3 x 5 = 15

4 x 5 = 20

5 x 5 = 25

6 x 5 = 30

7 x 5 = 35

8 x 5 = 40

9 x 5 = 45

10 x 5 = 50

Code of the program & screenshot of the output.


n=int(input("enter a number"))

for x in range(1,11):
table=x*n
print(str(x)+'*'+str(n)+'='+str(table))
8. Write a program to print the following pattern (hint: use nested loop)

12

123

1234

12345

Code of the program & screenshot of the output.


n=int(input("enter a number"))
for i in range(1,n+1):
k=1
for j in range(1,i+1):
print(k,end='')
k=k+1
print()
9. Write a program to create a copy of array and add an element to copied array . show
both arrays.
a. Program should accept an array from the user, swap the values of two arrays
and display it on the console

Eg: Output: Enter the size of Array 1

Input: 5

Output: Enter the values of Array 1

Array 1: 10, 20, 30, 40, 50

Array 2 : Copy of Array 1

Array 2 : 10, 20, 30, 40, 50 + add a element

Output : Array 1 [10, 20, 30, 40, 50 ]


Output : Array 2 [10, 20, 30, 40, 50, 60, 70 ]

Code of the program & screenshot of the output.


n=int(input('enter size'))
mylist = []
# Inserting values into the list
print('enter values')
for i in range(1,n+1):

mylist.insert(i, input())

#copying of list
mylist2=mylist.copy()
print(mylist2)

#insertion of value
print('enter value to insert')
mylist2.insert(n+2,input())
print(mylist2)
10. Write a program to sort an array in descending order without sort() and sorted()
Program should accept and array, sort the array values in descending order and display
it

● Selection
● Insertion
● bubble

Eg: Output: Enter the size of an array

Input: 5

Output: Enter the values of array

Input: 20, 10, 50, 30, 40

Output: Sorted array:


50, 40, 30, 20, 10

Code of the program & screenshot of the output.


n=int(input('enter a size'))
mylist=[]
print('enter values')
for x in range(0,n):
mylist.insert(x,int(input()))

for i in range(0,n-1):
for j in range(i+1,n):
if(mylist[i]<mylist[j]):
mylist[i],mylist[j]=mylist[j],mylist[i]
print(mylist)

11. Write a program to identify whether a string is a palindrome or not without using
reverse(), slicing
a. A string is a palindrome if it reads the same backward or forward eg:
MALAYALAM

Program should accept a string and display whether the string is a


palindrome or not

Eg: Output: Enter a string

Input: MALAYALAM

Output: Entered string is a palindrome

Eg 2: Output: Enter a string

Input: HELLO

Output: Entered string is not a palindrome

Code of the program & screenshot of the output


n=input('enter a name')
length=len(n)
flag=0
for i in range(0,length):
if(n[i]!=n[length-1-i]):

break
else:
flag=1

if (flag==1):
print('it is a palindrome')
else:
print('it is not palindrome')
12. Write a program to add to two dimensional arrays, understand the memory
management of list
a. Program should accept two 2D arrays and display its sum

Eg: Output: Enter the size of arrays

Input: 3

Output: Enter the values of array 1

Input:

123

456

789

Output: Enter the values of array 2

Input:
10 20 30

40 50 60

70 80 90

Output: Sum of 2 arrays is:

11 22 33

44 55 66

77 88 99

Code of the program & screenshot of the output.

x=int(input('enter the value for row:'))


y=int(input('enter the value for coloumn:'))
list=[]
for i in range(0,x):
list.append([])

for i in range(0,x):
for j in range(0,y):
list[i].append(j)

for i in range(0,x):
for j in range(0,y):
print('enter the value in row',i,'col:',j)
list[i][j]=int(input())

print('enter elements for array 2')


list2=[]
for i in range(0,x):
list2.append([])
for i in range(0,x):
for j in range(0,y):
list2[i].append(j)

for i in range(0,x):
for j in range(0,y):
print('enter value in row',i,'enter value in
coloumn',j)
list2[i][j]=int(input())

list3=[]
for i in range(0,x):
for j in range(0,y):
list3.append(list[i][j]+list2[i][j])

print(list3)
13. Grades are computed using a weighted average. Suppose that the written test counts
70%, lab exams 20% and assignments 10%.

If Arun has a score of

Written test = 81

Lab exams = 68

Assignments = 92

Arun’s overall grade = (81x70)/100 + (68x20)/100 + (92x10)/100 = 79.5

Write a program to find the grade of a student during his academic year.

a. Program should accept the scores for written test, lab exams and
assignments
b. Output the grade of a student (using weighted average)

Eg:

Enter the marks scored by the students

Written test = 55

Lab exams = 73

Assignments = 87

Grade of the student is 61.8

Code of the program & screenshot of the output

def writtentest():

x=int(input('enter written test value'))


testvalue=(x*70)/100

return testvalue

def labexams():

x=int(input("enter lab exams value"))

testvalue=(x*20)/100

return testvalue

def assignments():

x=int(input("enter assignments value"))

testvalue=(x*10)/100

return testvalue

a=writtentest()

b=labexams()

c=assignments()

def weightedavg():

x=a+b+c

print('average value is'+str(x))


weightedavg()

14. Study about functions


⮚ User defined
● Types of Arguments
⮚ Lambda
Write a program using user defined functions and lambda functions

Code of the program & screenshot of the output


x=int(input('énter 2 numbers'))
y=int(input())
#lambda function
subtract = lambda x, y: x-y
result=subtract(x,y)
print('subtracted value is'+str(result))
#user defined function
def addition(a,b):
sum=a+b
print('sum of the values are'+str(sum))

addition(x,y)

15. Write a program to accept an array and display it on the console using functions
a. Program should contain 3 functions including main() function

main()

1. Declare an array
2. Call function getArray()
3. Call function displayArray()

getArray()

1. Get values to the array

displayArray()

1. Display the array values

b. Study about global, local, non-local

Code of the program & screenshot of the output.


arr=[]

def getarray():

n= int(input('enter size of array'))


print('enter values')
for i in range(0,n):
arr.insert(i,int(input()))

def displayarray():
print(arr)

getarray()

displayarray()

16. Write a program to print “HELLO WORLD “using function without using print inside
of function. (“HELLO WORLD “must be inside Decorator function)

Code of the program & screenshot of the output.


def decorator(func):
def inner():
print('hello world')
func()
return inner

@decorator
def helloworld():
pass

helloworld()

17. Write a menu driven program to do the basic mathematical operations such as
addition, subtraction, multiplication and division (hint: use if else ladder or switch)
a. Program should have 4 functions named addition(), subtraction(),
multiplication() and division()
b. Should create a class object and call the appropriate function as user prefers
in the main function

Code of the program & screenshot of the output.


x=int(input('Enter 2 numbers'))
y=int(input())

class function:
def addition(a,b):
sum=a+b
print('you chose addition \n the result is '+str(sum))

def subtraction(a,b):
difference=a-b
print('you chose subtraction \n the result is
'+str(difference))

def multiplication(a,b):
result=a*b
print('you chose multiplication \n the result is
'+str(result))

def division(a,b):
result=(a%b)
print('you chose division \n the result is ' +str(result))

myobj=function

n=int(input('enter your choice'))

if n==1:

myobj.addition(x,y)
elif n==2:

myobj.subtraction(x,y)
elif n==3:

myobj.multiplication(x,y)
elif n==4:
myobj.division(x,y)

18. Write a program to print the following pattern using for loop

7 8 9 10

456

23

Code of the program & screenshot of the output.


k=11
for i in range(4,0,-1):
k=k-i
for j in range(0,i):
print(k,end=' ')
k=k+1

print()
k=k-i

19. Write a program to add the values of two 2D arrays


a. Program should contain a class, Functions should be inside the class

1. Call function getArray() using an object


2. Call function addArray() using an object
3. Call function displayArray() using an object

getArray()

1. Get values to the array

getArray()

1. Add array 1 and array 2


displayArray()

1. Display the array values

Eg:

Enter the size of array

Enter the values of array 1

1 2

3 4

Enter the values of array 2

5 6

7 8

Output:

Sum of array 1 and array 2:

6 8

10 12

Code of the program & screenshot of the output


arr=[]
arr2=[]
arr3=[]
class function:
def getarray():
x=int(input('enter number of rows'))
y=int(input('enter no. of coloumn'))

for i in range(0,x):
arr.append([])

for i in range(0,x):
for j in range(0,y):
arr[i].append(j)

print('enter values')
for i in range(0,x):
for j in range(0,y):
arr[i][j]=int(input())

# array2
for i in range(0,x):
arr2.append([])

for i in range(0,x):
for j in range(0,y):
arr2[i].append(j)
print('enter values for array 2')

for i in range(0,x):
for j in range(0,y):
arr2[i][j]=int(input())

# array 3
for i in range(0,x):
for j in range(0,y):
arr3.append(arr[i][j]+arr2[i][j])

def displayarr():
print('array 1 is',arr)
print('array 2 is',arr2)
print('sum of both arrays is',arr3)
obj=function
obj.getarray()
obj.displayarr()

20. Write a program to include all the functionalities of a calculator using ABSTRACT
class and abstract method. All the methods (add, sub, mul, div) should be inside of
abstract class. Abstract method definition should be in another class.

Examples :
from abc import ABC, abstractmethod
class Calculator(ABC):
def __init__(self, id, name):
self.id = id self.name = name
@abstractmethod
def add (self):
pass

Code of the program & screenshot of the output


from abc import ABC, abstractmethod
class abstractfunctions(ABC):
@abstractmethod
def addition(self):
pass
@abstractmethod
def subtraction(self):
pass
@abstractmethod
def multiplication(self):
pass
@abstractmethod
def division(self):
pass

class callfunctions(abstractfunctions):
def addition(self,a,b):
sum=a+b
print('sum is',sum)
def subtraction(self,a,b):
difference=a-b
print('difference is',difference)
def multiplication(self,a,b):
product=a*b
print('product is',product)
def division(self,a,b):
quotient=a%b
print('quotient is',quotient)

n=int(input('enter 2 numbers'))
m=int(input())

obj=callfunctions()
obj.addition(m,n)
obj.subtraction(m,n)
obj.multiplication(m,n)
obj.division(m,n)

21. Write a program to build a home. The Home class should define all the attributes of each room
in a home. From the Home class create two homes. FirstHome and SecondHome. First home
should have an extra study room as a method. SecondHome should have the work_area as an
extra method. should use the concept of inheritance.
class Home:
def __init__(self):
pass
def room1:
width=100
breadth = 100
print('are of room1',width*breath)
def kitchen:
width = 1222
breadth = 4888
print('are of kitchen',width*breath)
you should have mentioned all the plans of home here as methods.

Class FirstHome(Home):
# define the extra method's
pass
class SecondHome(Home):
# define the extra method's
pass

Code of the program & screenshot of the output


class home:

def room1(self):
width=100
breadth=100
area=width*breadth
print('area of room 1 is',area)

def kitchen(self):
width=50
breadth=50
area=width*breadth
print('area of kitchen is',area)

def bathroom(self):
width=25
breadth=25
area=width*breadth
print('area of bathroom is',area)

def room2(self):
width=100
breadth=100
area=width*breadth
print('area of room 2 is',area)
def kitchen2(self):
width=50
breadth=50
area=width*breadth
print('area of kitchen is',area)

def bathroom2(self):
width=25
breadth=25
area=width*breadth
print('area of bathroom is',area)

class firsthome(home):
def extrastudyroom(self):
print('this is studyroom')

class secondhome(home):
def workarea(self):
print('this is workarea')

obj1=firsthome()
obj1.room1()
obj1.bathroom()
obj1.kitchen()

obj2=secondhome()
obj2.room2()
obj2.bathroom2()
obj2.kitchen2()
22. Write a program to create Class with name and account number and implement get
and set, with property decorator and making account number and name private.

class account:
def __init__(self,name:str,number:int):
self._name=name
self._number=number

@property
def getname(self):
print(self._name,'is accepting')
return self._name

@getname.setter
def getname(self,value):
self._name=value
print('acoount name is',self._name)

@property
def getnumber(self):
return self._number

@getnumber.setter
def getnumber(self,value):
self._number=value
print('account number is',self._number)

obj=account('shafi',65465468489)
obj.getname='hathim'
obj.getnumber=2164654455

23. Write a function to calculate the sum of all numbers passed as its arguments. Your
function should be called sum_numbers and should define a single variable
argument (i.e. a star argument) that will get the values to sum.

Test the function with the following values:

Values Result
1, 2, 3 6
8, 20, 2 30
12.5, 3.147, 98.1 113.747
1.1, 2.2, 5.5 8.8
Code of the program & screenshot of the output

def add(*n):
total=sum(n)
print('sum is',float(total))

add()

24. pantry = {
"chicken": 500,
"lemon": 2,
"cumin": 24,
"paprika": 18,
"chilli powder": 7,
"yogurt": 300,
"oil": 450,
"onion": 5,
"garlic": 9,
"ginger": 2,
"tomato puree": 125,
"almonds": 75,
"rice": 500,
"coriander": 20,
"lime": 3,
"pepper": 8,
"egg": 6,
"pizza": 2,
"spam": 1,
}

recipes = {
"Butter chicken": [
"chicken",
"lemon",
"cumin",
"paprika",
"chilli powder",
"yogurt",
"oil",
"onion",
"garlic",
"ginger",
"tomato puree",
"almonds",
"rice",
"coriander",
"lime",
],
"Chicken and chips": [
"chicken",
"potatoes",
"salt",
"malt vinegar",
],
"Pizza": [
"pizza",
],
"Egg sandwich": [
"egg",
"bread",
"butter",
],
"Beans on toast": [
"beans",
"bread",
],
"Spam a la tin": [
"spam",
"tin opener",
"spoon",
],
}

observe the dictionary above and write a menu driven python program to create
recipes. Once one recipe is done then the quantity of the items in pantry should also be
reduced
Eg : If you cook beans on toast the beans quantity and bread quantity need to
decrease i.e., one from the total quantity each.
def cook_recipe(recipe_name):
recipe = recipe_name
if recipe is None:
print("Recipe not found.")
return

for ingredient in recipe:


if ingredient not in pantry:
print("Ingredient not found in the pantry.")

elif pantry[ingredient] == 0:
print("Ingredient is out of stock.")

for ingredient in recipe:


pantry[ingredient] -= 1

print("Successfully cooked . Enjoy your meal!")

25. create a custom exception class and raise this exception when user press one in the
menu and handles this exception.
try:
n=int(input('enter a number'))
if(n==1):
print('option 1 is not available at the moment')

except ValueError as e:
print('invalid input')
26. Write a list comprehension that returns the list ["1*2=1", "22=4", "32=9", ....,
"25*2=625"]
print([x*x for x in range(1,26)])
27. Using dict comprehension and a conditional argument create a dictionary from the
current dictionary where only the key:value pairs with value above 2000 will be taken
to the new dictionary.
dict1={"NFLX":4950,"TREX":2400,"FIZZ":1800, "XPO":1700}
dict2={}

dict1 = {"NFLX": 4950, "TREX": 2400, "FIZZ": 1800, "XPO": 1700}


dict2 = {key: value for key, value in dict1.items() if value >
2000}
print(dict2)

You might also like