Sie sind auf Seite 1von 28

Programming and Problem Solving L-1 Laboratory Work

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L-2 Laboratory Work

Programming and Problem Solving Laboratory


Technical PublicationsTM - An up thrust for knowledge
Programming and Problem Solving L-3 Laboratory Work

Experiment 1 : To calculate salary of employee given his basic pay(take as input from user). Calculate gross
salary of employee. Let HRA be 10% of basic pay and TA be 5% of the basic pay. Let employee
pay professional tax as 2% of total salary. Calculate net salary payable after deductions.
Solution :
print("Enter basic salary: ")
basic=float(input())
HRA=(basic*10)/100
TA=(basic *5)/100
gross_salary=basic+HRA+TA
print("Gross Salary is: ",gross_salary)
PTax=(gross_salary*2)/100
net_salary=gross_salary-PTax
print("Net Salary is:",net_salary)

Output
Enter basic salary:
10000
Gross Salary is: 11500.0
Net Salary is: 11270.0
>>>

Experiment 2 : To accept an object mass in kilogram and velocity in meters per second and display its
momentum. Momentum is calculated as e=mc 2 where m is the mass of the object and c is its
velocity.
Solution :
print("Enter mass of the object(kg)")
m=float(input())
print("Enter velocity of the object(m/s)")
c=float(input())
e=m*(c**2)
print("Momentum is: ",e)

Output
Enter mass of the object(kg)
10
Enter velocity of the object(m/s)
2.5
Momentum is: 62.5
>>>

Experiment 3 : To accept N numbers from user. Compute and display maximum in list, minimum in list, sum and
average of numbers.
Solution :
mylist = [] # start an empty list
print("Enter the value of N: ")
N = int(input()) # read number of element in the list
for i in range(N):
print("Enter the element: ")
new_element = int(input()) # read next element
mylist.append(new_element) # add it to the list

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L-4 Laboratory Work

print("The list is: ")


print(mylist)
print("The maximum element from list is: ")
max_element=mylist[0]
for i in range(N): #iterating throu list
if(mylist[i]>max_element):
max_element=mylist[i] #finding the maximum element

print(max_element)#printing the maximum element

print("The minimum element from list is: ")


min_element=mylist[0]
for i in range(N): #iterating throu list
if(mylist[i]<min_element):
min_element=mylist[i] #finding the minimum element

print(min_element)#printing the minimum element


print("The sum of all the numbers in the list is: ")
sum=0
for i in range(N): #iterating throu list
sum=sum+mylist[i] # finding the sum
print(sum)
avg=sum/N # computing the average
print("The Average of all the numbers in the list is: ",avg)

Output
Enter the value of N:
5
Enter the element:
33
Enter the element:
22
Enter the element:
55
Enter the element:
11
Enter the element:
44
The list is:
[33, 22, 55, 11, 44]
The maximum element from list is:
55
The minimum element from list is:
11
The sum of all the numbers in the list is:
165
The Average of all the numbers in the list is: 33.0
>>>

Experiment 4 : To accept student’s five courses marks and compute his/her result. Student is passing if he/she
scores marks equal to and above 40 in each course. If student scores aggregate greater than 75%,
then the grade is distinction. If aggregate is 60>= and <75 then the grade is first division. If

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L-5 Laboratory Work

aggregate is 50>= and <60then the grade is second division. If aggregate is 40>= and <50 then the
grade is third division.
Solution :
print("Enter the marks in English: ")
marks1=int(input())
print("Enter the marks in Mathematics: ")
marks2=int(input())
print("Enter the marks in Science: ")
marks3=int(input())
print("Enter the marks in Social Studies: ")
marks4=int(input())
print("Enter the marks in Computer Science: ")
marks5=int(input())
if(marks1<40 or marks2<40 or marks3<40 or marks4<40 or marks5<40 ):
print("Fail")#minimum requirement for passing
else:
total=marks1+marks2+marks3+marks4+marks5
avg=float(total)/5 #computing aggregate marks
print("The aggregate marks are: ",avg)
if(avg>=75):
print("Grade:Distinction")
elif(avg >=60 and avg<75):
print("Grade:First Division")
elif(avg>=50 and avg<60):
print("Grade:Second Division")
elif(avg>=40 and avg<50):
print("Grade:Third Division(pass)")
else:
print("Fail")

Output(Run1)
Enter the marks in English:
33
Enter the marks in Mathematics:
66
Enter the marks in Science:
55
Enter the marks in Social Studies:
66
Enter the marks in Computer Science:
44
Fail
>>>

Output(Run2)
Enter the marks in English:
67
Enter the marks in Mathematics:
89
Enter the marks in Science:
86
Enter the marks in Social Studies:

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L-6 Laboratory Work
79
Enter the marks in Computer Science:
90
The aggregate marks are: 82.2
Grade:Distinction
>>>

Experiment 5 : To check whether input number is Armstrong number of not. An Armstrong number is an integer
with three digits such that the sum of the cubes of its digits is equal to the number itself. Ex.371.
Solution :
print("Enter some number:")
num = int(input())
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while (temp >0):
digit = temp % 10
sum = sum + (digit ** 3)
temp //= 10
# display the result
if (num == sum):
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

Output(Run1)
Enter some number:
371
371 is an Armstrong number
>>>

Output(Run2)
Enter some number:
456
456 is not an Armstrong number
>>>

Experiment 6 : To simulate simple calculator that performs basic tasks such as addition, subtraction,
multiplication and division with special operations like computing x y and x!
Solution :
import math
def add(x, y):
return x + y

def sub(x, y):


return x - y

def mult(x, y):


return x * y
def div(x, y):
return x / y

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L-7 Laboratory Work
def x_pow_y(x,y):
return math.pow(x,y)
def x_factorial(x):
factorial = 1
if x == 0:
return factorial
else:
for i in range(1,x+ 1):
factorial = factorial*i
return factorial
while(True):
print("Main Menu")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.x^y")
print("6.x!")
print("7.Exit")
print("Enter your choice")
choice = int(input())

if choice == 1:
print("Enter first number")
num1 = int(input())
print("Enter second number: ")
num2 = int(input())

print(num1,"+",num2,"=", add(num1,num2))
elif choice == 2:
print("Enter first number")
num1 = int(input())
print("Enter second number: ")
num2 = int(input())
print(num1,"-",num2,"=", sub(num1,num2))
elif choice == 3:
print("Enter first number")
num1 = int(input())
print("Enter second number: ")
num2 = int(input())
print(num1,"*",num2,"=", mult(num1,num2))
elif choice == 4:
print("Enter first number")
num1 = int(input())
print("Enter second number: ")
num2 = int(input())
print(num1,"/",num2,"=", div(num1,num2))
elif choice == 5:
print("Enter first number")
num1 = int(input())
print("Enter second number: ")
num2 = int(input())

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L-8 Laboratory Work
print(num1,"^",num2,"=", x_pow_y(num1,num2))
elif choice == 6:
print("Enter a number")
num1 = int(input())
print(num1,"! = ", x_factorial(num1))
else:
print("Exiting")
break;

Output
Main Menu
1.Add
2.Subtract
3.Multiply
4.Divide
5.x^y
6.x!
7.Exit
Enter your choice
1
Enter first number
10
Enter second number:
20
10 + 20 = 30
Main Menu
1.Add
2.Subtract
3.Multiply
4.Divide
5.x^y
6.x!
7.Exit
Enter your choice
3
Enter first number
2
Enter second number:
4
2*4=8
Main Menu
1.Add
2.Subtract
3.Multiply
4.Divide
5.x^y
6.x!
7.Exit
Enter your choice
6
Enter a number
4
4 ! = 24
Main Menu
1.Add
2.Subtract
Technical PublicationsTM - An up thrust for knowledge
Programming and Problem Solving L-9 Laboratory Work
3.Multiply
4.Divide
5.x^y
6.x!
7.Exit
Enter your choice
5
Enter first number
5
Enter second number:
4
5 ^ 4 = 625.0
Main Menu
1.Add
2.Subtract
3.Multiply
4.Divide
5.x^y
6.x!
7.Exit
Enter your choice
7
Exiting
>>>

Experiment 7 : To accept the number and compute a) square root of a number b) Square of number c) Cube of a
number d) Check for prime e) factorial of number f) prime factors
Solution :
import math
def sqrt_num(x):
return math.sqrt(x)

def sq_num(x):
return x*x

def cube_num(x):
return x * x *x

def isPrime(x):
if x > 1:
#check for factors
for i in range(2,x):
if (x % i) == 0: #factors exists
return False #hence it is not prime
else:
return True
else:
return False

def x_factorial(x):
factorial = 1
if x == 0:
return factorial
else:
Technical PublicationsTM - An up thrust for knowledge
Programming and Problem Solving L - 10 Laboratory Work
for i in range(1,x+ 1):
factorial = factorial*i #multipying by subsequent number
return factorial

def prime_factors(x):
# Print the number of two's that divide x
while x % 2 == 0:
print ("2")
x=x/2

# x must be odd at this point


# so a skip of 2 ( i = i + 2) can be used
for i in range(3,int(math.sqrt(x))+1,2):

# while i divides x , print i and divide x


while x % i== 0:
print(i)
x=x/i

# Condition if n is a prime
# number greater than 2
if x > 2:
print(x)

while(True):
print("Main Menu")
print("1.Square root")
print("2.Square")
print("3.Cube")
print("4.Check for Prime")
print("5.Factorial")
print("6.Prime Factors")
print("7.Exit")
print("Enter your choice")
choice = int(input())

if choice == 1:
print("Enter a number")
num = int(input())
print("Square Root of ",num,"is: ", sqrt_num(num))
elif choice == 2:
print("Enter a number")
num = int(input())
print("Square of ",num,"is: ", sq_num(num))
elif choice == 3:
print("Enter a number")
num = int(input())
print("Cube of ",num,"is: ", cube_num(num))
elif choice == 4:
print("Enter a number")
num = int(input())
if(isPrime(num)):

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 11 Laboratory Work
print(num," is a prime number")
else:
print(num," is not a prime number")
elif choice == 5:
print("Enter a number")
num = int(input())
print("Factorial of ",num," is: ", x_factorial(num))
elif choice == 6:
print("Enter a number")
num = int(input())
prime_factors(num)
else:
print("Exitting")
break;

Output
Main Menu
1.Square root
2.Square
3.Cube
4.Check for Prime
5.Factorial
6.Prime Factors
7.Exit
Enter your choice
1
Enter a number
25
Square Root of 25 is: 5.0
Main Menu
1.Square root
2.Square
3.Cube
4.Check for Prime
5.Factorial
6.Prime Factors
7.Exit
Enter your choice
2
Enter a number
4
Square of 4 is: 16
Main Menu
1.Square root
2.Square
3.Cube
4.Check for Prime
5.Factorial
6.Prime Factors
7.Exit
Enter your choice
4
Enter a number
7
7 is a prime number

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 12 Laboratory Work
Main Menu
1.Square root
2.Square
3.Cube
4.Check for Prime
5.Factorial
6.Prime Factors
7.Exit
Enter your choice
5
Enter a number
5
Factorial of 5 is: 120
Main Menu
1.Square root
2.Square
3.Cube
4.Check for Prime
5.Factorial
6.Prime Factors
7.Exit
Enter your choice
6
Enter a number
12
2
2
3.0
Main Menu
1.Square root
2.Square
3.Cube
4.Check for Prime
5.Factorial
6.Prime Factors
7.Exit
Enter your choice
7
Exitting
>>>

Experiment 8 : To accept two numbers from user and compute smallest divisor and Greatest Common Divisor of
these two numbers

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 13 Laboratory Work
Solution :
def LCM(a,b):
if(a>b):
greater = a
else:
greater = b
while(True):
if((greater%a==0) and (greater%b==0)):
ans=greater
break
greater=greater+1

return ans

def GCD(a,b):
if(a<b):
smaller = a
else:
smaller = b
for i in range(1,smaller+1):
if((a%i==0) and (b%i==0)):
ans=i
return ans

print("Enter a: ")
a=int(input())
print("Enter b:")
b=int(input())
print("LCM is ",LCM(a,b))
print("GCD is ",GCD(a,b))

Output
Enter a:
12
Enter b:
15
LCM is 60
GCD is 3
>>>

Experiment 9 : To accept numbers from user and print digits of number in reverse order.
Solution :
print("Enter some number")
n=int(input())
reverse=0
while (n >0):
reminder = n %10
reverse = (reverse *10) + reminder
n = n //10
print("The reversed number is: ",reverse)

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 14 Laboratory Work

Output
Enter some number
1234
The reversed number is: 4321

Experiment 10 : To input binary number from user and convert it to decimal number
Solution :
print("Enter a binary number: ")
binary = list(input())
value = 0

for i in range(len(binary)):
digit = binary.pop()#reading each digit of binary number from LSB
if digit == '1':#if it is 1
value = value + pow(2, i) #then get 2^i and add it to value
print("The decimal value of the number is", value)

Output
Enter a binary number:
1100
The decimal value of the number is 12
>>>

Experiment 11 : To generate pseudo random numbers


Solution :
import random
print(random.randint(0,100))

Output
39
>>>

Experiment 12 : To accept list of N integers and partition list into two sub lists even and odd numbers
Solution :
numlist = []
print("Enter total number of elements: \t")
n = int(input())
for i in range(1, n+1):
print("Enter element:")
element = int(input())
numlist.append(element)

evenlist = []
oddlist = []

for j in numlist:
if j % 2 == 0:
evenlist.append(j)
else:
oddlist.append(j)

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 15 Laboratory Work
print("Even numbers list \t", evenlist)
print("Odd numbers list \t", oddlist)

Output
Enter total number of elements:
5
Enter element:
11
Enter element:
22
Enter element:
33
Enter element:
44
Enter element:
55
Even numbers list [22, 44]
Odd numbers list [11, 33, 55]
>>>

Experiment 13 : To accept the numbers of terms a finds the sum of sine series
Solution :

We will first understand what the sine series is –


Sine series is a series used to find the value of sin(x) where x is the angle which is in radians and not in
degrees. If the angle is given in degrees(which is the usual practice of specifying the angle)then it should
be converted to radian.
The formula used to compute sine series is

x 2 n 1
sin x =  ( 1)
x 0
n
( 2 n  1)!

i.e.
x 3 x 5 x7
sinx = x     .....
3! 5! 7!
Consider x=900 . If we convert it to radian then
x in radian = angle*Pi/180
= 90*3.14159/180
= 1.5707
1.507 3 1.5707 5 1.5707 7
 sin(1.5707) = 1.507    + ……
3! 5! 7!
= 1.00
Let us now see the Python program based on this computation
import math
print("Enter the value for x in degree : ")
x=float(input())

print(" Enter the value for n : ")


n=int(input())

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 16 Laboratory Work
x=x*3.14159/180 #conversion of degree to radian
print("Angle in radian is: ",x)#displaying angle in radian
sum=0#initializing sum by zero

# Loop to calculate the value of Sine

for i in range(n):
sign=(-1)**i
sum = sum+((x**(2.0*i+1))/math.factorial(2*i+1))*sign

print("Sum of Sine series is: ",sum)

Output
Enter the value for x in degree :
90
Enter the value for n :
3
Angle in radian is: 1.570795
Sum of Sine series is: 1.004524829039292
>>>

Experiment 14 : To accept from user the number of Fibonacci numbers to be generated and print the Fibonacci
series.
Solution :
def fibonacci(n):
a=0
b=1

print("fibonacci series is:")


print(a, ",", b, end=", ") #displaying first two elements of series

for i in range(2, n):


c = a + b #getting third element
print(c, end=", ")

a=b
b=c

print("Enter number of elements you want in series (minimum 2): ")


n = int(input())
fibonacci(n)# Call to the function

Output
Enter number of elements you want in series (minimum 2):
10
fibonacci series is:
0 , 1, 1, 2, 3, 5, 8, 13, 21, 34,
>>>

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 17 Laboratory Work

Experiment 15 : Write a python program that accepts a string from user and perform following string operations –
i) Calculate length of string ii) String reversal

iii) Equality check of two strings iv) Check palindrome v) Check substring
Solution :
def str_len(str):
len = 0
for i in str:
len = len+1
return len

def str_rev(str):
return str[::-1]

def str_cmp(str1,str2):
if(str1==str2):
return True
else:
return False

def is_palindrome(str):
# Calling reverse function
rev = str_rev(str)

# Checking if both string are equal or not


if (str == rev):
return True
return False

def is_substr(str1,str2):
if(str1.find(str2)==-1):
return -1
else:
position=str1.find(str2)
return position

while(True):
print("Main Menu")
print("1.Calculate Length of String")
print("2.String Reversal")
print("3.Equality Check of two strings")
print("4.Check for Palindrome")
print("5.Check substring")
print("6.Exit")
print("Enter your choice")
choice = int(input())

if choice == 1:
print("Enter some string: ")

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 18 Laboratory Work
str = input()
print("Length of String: ",str,"is: ", str_len(str))
elif choice == 2:
print("Enter some string: ")
str = input()
print("Reversal of String: ",str,"is: ", str_rev(str))
elif choice == 3:
print("Enter first string: ")
str1 = input()
print("Enter second string: ")
str2 = input()
if(str_cmp(str1,str2)):
print("Two Strings are equal")
else:
print("Two Strings are not equal")
elif choice == 4:
print("Enter some string: ")
str = input()
if(is_palindrome(str)):
print("String ",str," is palindrome")
else:
print("String ",str," is not palindrome")
elif choice == 5:
print("Enter some String: ")
str1 = input()
print("Enter some substring: ")
str2 = input()
if((is_substr(str1,str2))<0):
print("String: ",str2," is not a substring of: ",str1)
else:
print("The substring is found at position: ",is_substr(str1,str2))

else:
print("Exiting")
break;

Output
Main Menu
1.Calculate Length of String
2.String Reversal
3.Equality Check of two strings
4.Check for Palindrome
5.Check substring
6.Exit
Enter your choice
1
Enter some string:
Python
Length of String: Python is: 6
Main Menu
1.Calculate Length of String
2.String Reversal
3.Equality Check of two strings
4.Check for Palindrome
Technical PublicationsTM - An up thrust for knowledge
Programming and Problem Solving L - 19 Laboratory Work
5.Check substring
6.Exit
Enter your choice
2
Enter some string:
Python
Reversal of String: Python is: nohtyP
Main Menu
1.Calculate Length of String
2.String Reversal
3.Equality Check of two strings
4.Check for Palindrome
5.Check substring
6.Exit
Enter your choice
3
Enter first string:
abc
Enter second string:
abc
Two Strings are equal
Main Menu
1.Calculate Length of String
2.String Reversal
3.Equality Check of two strings
4.Check for Palindrome
5.Check substring
6.Exit
Enter your choice
4
Enter some string:
madam
String madam is palindrome
Main Menu
1.Calculate Length of String
2.String Reversal
3.Equality Check of two strings
4.Check for Palindrome
5.Check substring
6.Exit
Enter your choice
5
Enter some String:
I eat a mango
Enter some substring:
eat
The substring is found at position: 2
Main Menu
1.Calculate Length of String
2.String Reversal
3.Equality Check of two strings
4.Check for Palindrome
5.Check substring
6.Exit
Enter your choice
6
Exiting
Technical PublicationsTM - An up thrust for knowledge
Programming and Problem Solving L - 20 Laboratory Work
>>>

Experiment 16 : To copy contents of one file to another. While copying a) all full stops are replaced with commas
b) lower case are replaced by upper case c) upper case are to be replaced with lower case.
Solution :
def replace_dot(file1):
file2=open("d:\\Replacedot.txt","w")
text=file1.readline()
while text:
word=text.split() #creating a list of words
word = [w.replace('.', ',') for w in word]#searching dot from each word and replacing it by comma
text=' '.join(word)#creating a sentence again from list of words
text+='\n'
file2.write(text)#writing the content to the file
text=file1.readline()#reading file line by line in a loop
file1.close()
file2.close()

def to_lower_case(file1):
file2=open("d:\\lowercase.txt","w")
text=file1.readline()
while text:
word=text.split()
word = [w.lower() for w in word] #converting each word to lower case
text=' '.join(word)
text+='\n'
file2.write(text)
text=file1.readline()
file1.close()
file2.close()

def to_upper_case(file1):
file2=open("d:\\uppercase.txt","w")
text=file1.readline()
while text:
word=text.split()
word = [w.upper() for w in word] #converting each word to upper case
text=' '.join(word)
text+='\n'
file2.write(text)
text=file1.readline()
file1.close()
file2.close()

file1=open("d:\\Original.txt","r")
replace_dot(file1)
print("The dots are replaced by commas in the file")

file1=open("d:\\Original.txt","r")
to_lower_case(file1)
print("The upper case letters are converted to lower case")
Technical PublicationsTM - An up thrust for knowledge
Programming and Problem Solving L - 21 Laboratory Work

file1=open("d:\\Original.txt","r")
to_upper_case(file1)
print("The lower case letters are converted to upper case")

Output

original.txt

Replacedot.txt lowercase.txt

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 22 Laboratory Work

uppercase.txt

Experiment 17 : To count total characters in file, total words in file, total lines in file and frequency of given word
in file.
Solution :
from collections import Counter
def word_count(fname):
count=0
with open(fname,'r') as f:
for line in f:
word=line.split()
count+=len(word)
f.close()
return count

def char_count(fname):
count=0
with open(fname,'r') as f:
for line in f:
word=line.split()
count+=len(line)
f.close()
return count

def line_count(fname):
count=0
with open(fname,'r') as f:
for line in f:
word=line.split()
count+=1
f.close()
return count

def freq_word_count(fname):
with open(fname) as f:
return Counter(f.read().split())

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 23 Laboratory Work
print("Number of characters in the file :\n",char_count("d:\\test.txt"))
print("Number of words in the file :\n",word_count("d:\\test.txt"))
print("Number of lines in the file :\n",line_count("d:\\test.txt"))
print("Number of words with frequency count in the file :\n",freq_word_count("d:\\test.txt"))

Output
umber of characters in the file :
181
Number of words in the file :
32
Number of lines in the file :
5
Number of words with frequency count in the file :
Counter({'to': 3, 'This': 2, 'line': 2, 'is': 2, 'file.': 2, 'the': 2, 'Introduction': 1, 'File': 1, 'operations.': 1, 'Reading': 1, 'and': 1, 'Writing':
1, 'file': 1, 'operations': 1, 'in': 1, 'Python': 1, 'are': 1, 'easy': 1, 'understand.': 1, 'We': 1, 'enjoy': 1, 'it.': 1, 'written': 1, 'last': 1, 'of': 1})
>>>

Experiment 18 : Create class EMPLOYEE for storing details(Name, designation, gender, Date of joining and
Salary). Define function members to compute a) total number of employees in an organization b)
Count of male and female employee c) Employee with salary more than 10,000 d) Employee with
designation “Asst Manager”
Solution :
class Employee:
count=0
female_count=0
male_count=0
salary_count=0
desig_count=0
def __init__(self,name,desig,gender,doj,salary):
self.name=name
self.desig=desig
self.gender=gender
self.doj=doj
self.salary=salary
Employee.count+=1
if(self.gender=="F"):
Employee.female_count+=1
else:
Employee.male_count+=1
if(self.salary>10000):
Employee.salary_count+=1
if(self.desig =="Asst_manager"):
Employee.desig_count+=1

def display_emp_count(self):
print("There are ",Employee.count, " employees in the organization")
def count_gender(self):
print("There are ",Employee.female_count, " female employees in the organization")
print("There are ",Employee.male_count, " male employees in the organization")
def count_big_salary(self):
print("There are ",Employee.salary_count, " employees in the organization having salary >10000")
def count_desig(self):

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 24 Laboratory Work
print("There are ",Employee.desig_count, " employees in the organization with designation 'Asst_manager' ")

#Entering data for Employee class


e1=Employee("Chitra","manager","F","1-2-2001",50000)
e2=Employee("Ankita","Asst_manager","F","23-5-2007",20000)
e3=Employee("Varsha","Accountant","F","11-9-2010",10000)
e4=Employee("Rahul","HR","M","24-3-2012",30000)
e5=Employee("Aditya","Asst_manager","M","14-7-2009",20000)

e5.display_emp_count()
e5.count_gender()
e5.count_big_salary()
e5.count_desig()

Output
There are 5 employees in the organization
There are 3 female employees in the organization
There are 2 male employees in the organization
There are 4 employees in the organization having salary >10000
There are 2 employees in the organization with designation 'Asst_manager'
>>>

Experiment 19 : Create a class STORE to keep track of Products(product Code, Name and price).Display menu of
all products to user. Generate bill as per order.
Solution :
class STORE:
__product_code = []
__name = []
__price =[]

def input_data(self):
for i in range(3):
self.__product_code.append(int(input("Enter the code of product: ")))
self.__name.append(input("Enter the name of product: "))
self.__price.append(float(input("Enter the price of product: ")))
def display_data(self):
print("Product code\t Name \t Price")
for i in range(3):
print(self.__product_code[i],"\t\t",self.__name[i],"\t\t\t",self.__price[i])
def generate_bill(self,qty):
total_amount=0
for i in range(3):
total_amount= total_amount+self.__price[i]*qty[i]
print("\t\t###### BILL #######")
print("Code \t Name\t Price \t Qty \t Subtotal")
for i in range(3):
print(self.__product_code[i],"\t",self.__name[i],"\t\t",self.__price[i],"\t",qty[i],"\t",self.__price[i]*qty[i])
print("----------------------------------------------------")
print("Total = ",total_amount)

s=STORE()
s.input_data()

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 25 Laboratory Work
s.display_data()
qty=[]
for i in range(3):
print("Enter the quantity for each product")
qty.append(int(input()))

s.generate_bill(qty)

Output
Enter the code of product: 101
Enter the name of product: pen
Enter the price of product: 20
Enter the code of product: 102
Enter the name of product: pencil
Enter the price of product: 5
Enter the code of product: 103
Enter the name of product: eraser
Enter the price of product: 2
Product code Name Price
101 pen 20.0
102 pencil 5.0
103 eraser 2.0
Enter the quantity for each product
10
Enter the quantity for each product
25
Enter the quantity for each product
15
###### BILL #######
Code Name Price Qty Subtotal
101 pen 20.0 10 200.0
102 pencil 5.0 25 125.0
103 eraser 2.0 15 30.0
---------------------------------------------------
Total = 355.0
>>>

Experiment 20 (Mini Project) : Program that simulates rolling dice. When the program runs, it will randomly choose
the numbers between 1 and 6(or other integer you prefer). Print that number. Request user to roll
again. Set the min and max number that dice can show. For the average die, that means a
minimum of 1 and maximum of 6.
Solution :
import random
min = 1
max = 6

roll_again = "yes"

while roll_again == "yes" or roll_again == "y":


print("Rolling the dice...")
print("The value is....")
print(random.randint(min, max))

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 26 Laboratory Work
roll_again = input("Do you want to Roll the dice again?")

Output
Rolling the dice...
The value is....
6
Do you want to Roll the dice again?y
Rolling the dice...
The value is....
2
Do you want to Roll the dice again?y
Rolling the dice...
The value is....
6
Do you want to Roll the dice again?y
Rolling the dice...
The value is....
4
Do you want to Roll the dice again?n
>>>

Experiment 21(Mini Project):

Guess Number: Randomly generate a number unknown to the user. The user needs to guess what
that number is. If user’s guess is wrong, the program should return some sort of indication as to
how wrong(e.g. the number is too high or too low). If the user guesses correctly, a positive
indication should appear. Write functions to check if the user input is an actual number, to see the
difference between the inputted number and the randomly generated numbers and to then compare
the numbers
Solution :
import random
randomNumber = random.randrange(0,100)
print("Random number has been generated")
guessed = False
while guessed==False:
num = int(input("Enter some guess: "))
if num==randomNumber:
guessed = True
print("Well done!You have guessed a number correctly!!!")
elif num>100 and num <0:
print("Our guess is not between 0 and 100")
elif num>randomNumber:
print("Number is high")
elif num < randomNumber:
print("Number is low")

Output
Random number has been generated
Enter some guess: 55
Number is low
Enter some guess: 80

Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 27 Laboratory Work
Number is high
Enter some guess: 65
Number is high
Enter some guess: 60
Number is low
Enter some guess: 62
Number is low
Enter some guess: 64
Well done!You have guessed a number correctly!!!
>>>



Technical PublicationsTM - An up thrust for knowledge


Programming and Problem Solving L - 28 Laboratory Work

Notes

Technical PublicationsTM - An up thrust for knowledge

Das könnte Ihnen auch gefallen