You are on page 1of 45

Mahaveer Institute of Science and Technology

Ex. No. : 1
Date:

Aim: To write a program to demonstrate different number data types in Python.

Algorithm:

Begin
1. A←100
2. b←10.23
3. c←100+3j
4. d←”Hello Python”
5. e←[2,4,6,8]
6. f←("hello", 1,2,3,"go")
7. g← {1:"Jan",2:"Feb", 3:"March"}
8. write type(a)
9. write type(b)
10. write type(c)
11. write type(d)
12. write type(e)
13. write type(f)
14. write type(g)
End

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Program:

a=100
b=10.23
c=100+3j
d=”Hello Python”
e=[2,4,6,8]
f=("hello", 1,2,3,"go")
g= {1:"Jan",2:"Feb", 3:"March"}

print("The type of variable having value", a, " is ", type(a))


print("The type of variable having value", b, " is ", type(b))
print("The type of variable having value", c, " is ", type(c))
print("The type of variable having value '", d, "' is ", type(d))
print("The type of variable having value", e, " is ", type(e))
print("The type of variable having value", f, " is ", type(f))
print("The type of variable having value", g, " is ", type(g))

Output

The type of variable having value 100 is <class 'int'>


The type of variable having value 100.23 is <class 'float'>
The type of variable having value (100+3j) is <class 'complex'>
The type of variable having value ' Hello Python ' is <class 'str'>
The type of variable having value [2, 4, 6, 8] is <class 'list'>
The type of variable having value ('hello', 1, 2, 3, 'go') is <class 'tuple'>
The type of variable having value {1: 'Jan', 2: 'Feb', 3: 'March'} is <class 'dict'>

Result: The program was executed successfully and verified the output

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Ex. No. : 2
Date:

Aim: To write a program to perform different Arithmetic Operations on numbers in Python.

Algorithm:

Begin
1. while True
begin
2. write "Operation to perform:"
3. write "1. Addition"
4. write “2. Subtraction"
5. write "3. Multiplication"
6. write "4. Division"
7. write "5. Raising a power to number"
8. write "6. Floor Division”
9. write "7. Modulus or Remainder Division"
10. write "8. Exit"
11. Read choice
12. If choice =='8'
13. stop
14. Read num1
15. Read num2
16. if choice == '1'
17. Write 'Sum of ', num1, "and" ,num2, "=", num1 + num2
18. elif choice == '2'
19. Write 'Difference of ',num1, "and", num2, "=", num1 - num2
20. elif choice == '3'
21. Write 'Multiplication of',num1, "and", num2, "=", num1 * num2
22. elif choice == '4'
23. Write 'Division of',num1, "and", num2, "=", num1 / num2
24. elif choice == '5'
25. Write 'Exponent of ',num1, "**", num2, "=", num1 ** num2
26. elif choice == '6'
27. Write 'Floor Division of ',num1, "//",num2, "=", num1 // num2
28. elif choice == '7'
29. Write 'Modulus of ',num1, "%",num2, "=", num1 % num2
end
End

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Program:

while True:
print("\n\n\n");
print("Operation to perform:");
print("1. Addition");
print("2. Subtraction");
print("3. Multiplication");
print("4. Division");
print("5. Raising a power to number");
print("6. Floor Division");
print("7. Modulus or Remainder Division");
print("8. Exit");
choice = input("Enter choice: ");

if choice =='8':
break;

num1 = int(input("Enter first number: "));


num2 = int(input("Enter second number: "));

if choice == '1':
print('Sum of ', num1, "and" ,num2, "=", num1 + num2);

elif choice == '2':


print('Difference of ',num1, "and", num2, "=", num1 - num2);

elif choice == '3':


print('Multiplication of',num1, "and", num2, "=", num1 * num2);

elif choice == '4':


print('Division of',num1, "and", num2, "=", num1 / num2);

elif choice == '5':


print('Exponent of ',num1, "**", num2, "=", num1 ** num2);

elif choice == '6':


printf('Floor Division of ',num1, "//",num2, "=", num1 // num2);

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

elif choice == '7':


print('Modulus of ',num1, "%",num2, "=", num1 % num2);

Output:

Operation to perform:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Raising a power to number
6. Floor Division
7. Modulus or Remainder Division
8. Exit
Enter choice: 5
Enter first number: 2
Enter second number: 4
Exponent of 2 ** 4 = 16

Operation to perform:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Raising a power to number
6. Floor Division
7. Modulus or Remainder Division
8. Exit
Enter choice: 6
Enter first number: 43
Enter second number: 4
Floor Division of 43 // 4 = 10

Operation to perform:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Raising a power to number
6. Floor Division

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

7. Modulus or Remainder Division


8. Exit
Enter choice: 7
Enter first number: 44
Enter second number: 5
Modulus of 44 % 5 = 4

Result: The program was executed successfully and verified the output

Ex. No. : 3
Date:

Aim: To write a program to create, concatenate and print a string and accessing sub-string from a
given string.

Algorithm:

Begin
1. s1←'string in single quote'
2. s2←"string in double quote"
3. s3←"""string in triple quote"""
4. s4←'.'
5. s5←'Newsletter'
6. // Printing string
7. write s1
8. write s2
9. write s3
10.s6←s1+s2+s3
11. write "Concatenated string = ",s6
12.Write "Fruits are Apple,Orange,Grape,etc",s4*3
13. //substring or slicing
14.Write "Substring of ",s5," = ",s5[4:7]
15.Write "Substring of ",s5," = ",s5[:4]
16.Write "Substring of ",s5," = ",s5[4:]
17.Write "Substring of ",s5," = ",s5[::2]
18.Write "Substring of ",s5," = ",s5[-6:-1]
19.Write "Substring of ",s5," = ",s5[-6:]
20.Write "Substring of ",s5," = ",s5[-10:-6]
21.Write "Reverse of ",s5," = ",s5[::-1]
End

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Program:

# String creation
s1='string in single quote'
s2="string in double quote"
s3="""string in triple quote"""
s4='.'
s5='Newsletter'

# Printing string
print(s1)
print(s2)
print(s3)

#string concatenation
s6=s1+s2+s3
print("Concatenated string = ",s6)
print("Fruits are Apple,Orange,Grape,etc",s4*3)

#substring or slicing
print("Substring of ",s5," = ",s5[4:7])
print("Substring of ",s5," = ",s5[:4])
print("Substring of ",s5," = ",s5[4:])
print("Substring of ",s5," = ",s5[::2])
print("Substring of ",s5," = ",s5[-6:-1])
print("Substring of ",s5," = ",s5[-6:])
print("Substring of ",s5," = ",s5[-10:-6])
print("Reverse of ",s5," = ",s5[::-1])

Output:
string in single quote
string in double quote

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

string in triple quote


Concatenated string = string in single quotestring in double quotestring in tripple
quote
Fruits are Apple,Orange,Grape,etc ...
Substring of Newsletter = let
Substring of Newsletter = News
Substring of Newsletter = letter
Substring of Newsletter = Nwlte
Substring of Newsletter = lette
Substring of Newsletter = letter
Substring of Newsletter = News
Reverse of Newsletter = rettelsweN

Result: The program was executed successfully and verified the output
Ex. No. : 4
Date:

Aim: To write a program to print the current date in the following format “Sun May 29
02:26:23 IST 2017”

Algorithm:

Begin
1. today←datetime.date.today()
2. Write "Today date and time:", today.ctime()
3. Write "Cureent Year: ",datetime.date.today().strftime("%Y")
4. Write "Cureent Year: ",datetime.date.today().strftime("%B")
5. Write "Weakday of the year: ",datetime.date.today().strftime("%w")
6. Write "Day of the month: ",datetime.date.today().strftime("%d")
7. Write "Day of the week: ",datetime.date.today().strftime("%A")
End

Program:

import datetime
import time

today = datetime.date.today()
print("Today date and time:", today.ctime())
print(datetime.datetime.now())
print("Cureent Year: ",datetime.date.today().strftime("%Y"))
print("Cureent Year: ",datetime.date.today().strftime("%B"))
print("Weakday of the year: ",datetime.date.today().strftime("%w"))

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

print("Day of the month: ",datetime.date.today().strftime("%d"))


print("Day of the week: ",datetime.date.today().strftime("%A"))

Output:

Today date and time: Tue Jul 2 00:00:00 2019


2019-07-02 15:55:54.812774
Cureent Year: 2019
Cureent Year: July
Weakday of the year: 2
Day of the month: 02
Day of the week: Tuesday

Result: The program was executed successfully and verified the output
Ex. No. : 5
Date:

Aim: To write a program to create, append, and remove lists in python.

Algorithm:
Begin
1. lst = []
2. choice←1
3. while choice!=0
begin
4. write "0. Exit"
5. write "1. Add"
6. Write "2. Delete"
7. Write "3. Display"
end
8. Read choice
9. if choice==1
begin
10. Read n
11. lst.append(n)
12. Write "List: ",lst
end
13.elif choice==2
begin
14. if len(lst)==0
begin

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

15. Write "List is empty, no item to remove:"


16. Continue
end
end

17. Read n
18.if n not in lst
begin
19. Write "The item to be removed not in list:"
20. Continue
end
21.lst.remove(n)
22.Write "List: ",lst
23.elif choice==3
24. print("List: ",lst)
25.elif choice==0
26. Write "Exiting!"
27.else:
28.write "Invalid choice!!"
End
Program:

lst = []
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Delete")
print("3. Display")
choice=int(input("Enter choice: "))
if choice==1:
n=int(input("Enter number to append: "))
lst.append(n)
print("List: ",lst)
elif choice==2:
#if lst=[]:
# print("List is empty, no item to remove:")
# continue

#if not lst:


# print("List is empty, no item to remove:")
# continue

if len(lst)==0:
print("List is empty, no item to remove:")

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

print()
continue

n=int(input("Enter number to remove: "))


if n not in lst:
print("The item to be removed not in list:")
print()
continue
lst.remove(n)
print("List: ",lst)

elif choice==3:
print("List: ",lst)

elif choice==0:
print("Exiting!")

else:
print("Invalid choice!!")
print()

Output:

0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 10
List: [10]

0. Exit
1. Add
2. Delete
3. Display
Enter choice: 3
List: [10]

0. Exit
1. Add
2. Delete
3. Display
Enter choice: 2
Enter number to remove: 10

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

List: []

0. Exit
1. Add
2. Delete
3. Display
Enter choice: 2
List is empty, no item to remove:

0. Exit
1. Add
2. Delete
3. Display
Enter choice: 0
Exiting!

Result: The program was executed successfully and verified the output

Ex. No. : 6
Date:

Aim: To write a program to demonstrate working with tuples in python.

Algorithm:
1. tup1 ←
('jan','feb','mar','apr','may','june','july','august','september','october','november','december' )
2. tup2 ← (1, 2, 3, 4, 5)
3. tup3←(1, "Hello", (11, 22, 33))
4. tup4←('India',[10,20,30],'USA')
5. #print the tuple
6. print(tup1)
7. #iterating in tuple
8. for mon in tup1
9. write mon
10.#accessing the tuple element
11.Write "The element in the 5th position : ",tup1[5]
12.Write tup1[-6]
13. Write "Tuple before addition"
14.Write tup2
15.tup2 = tup2 + (7,)

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

16.write "Tuple after addition"


17.write tup2
18.tup2=tup2+('apple','orange','banana')
19.write tup2
20.#accessing nested tuple element
21.Write tup3[2][1]
22.#tuple element is mutable, element change is possible
23.Write "Tuple before change"
24.Write tup4
25.tup4[1][2]=40
26.write "Tuple after change"
27.write tup4
28.#Slicing operation in tuples
29.Write tup1[2:5]
30.Write tup1[4:]
31.Write tup1[:4]
32.#finding position of the element
33.Write "The position of 'october' in the tuple: ",tup1.index('october')

Program:
tup1 = ('jan','feb','mar','apr','may','june','july','august','september','october','november','december' )
tup2 = (1, 2, 3, 4, 5)
tup3=(1, "Hello", (11, 22, 33))
tup4=('India',[10,20,30],'USA')

#print the tuple


print(tup1)

#iterating in tuple
for mon in tup1:
print(mon,end=' ')
print()

#accessing the tuple element


print("The element in the 5th position : ",tup1[5])
print(tup1[-6])

print("Tuple before addition")

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

print(tup2)
tup2 = tup2 + (7,)
print("Tuple after addition")
print(tup2)

tup2=tup2+('apple','orange','banana')
print(tup2)

#accessing nested tuple element


print(tup3[2][1])

#tuple element is mutable, element change is possible


print("Tuple before change")
print(tup4)
tup4[1][2]=40
print("Tuple after change")
print(tup4)

#Slicing operation in tuples


print(tup1[2:5])
print(tup1[4:])
print(tup1[:4])

#finding position of the element


print("The position of 'october' in the tuple: ",tup1.index('october'))

Output:

('jan', 'feb', 'mar', 'apr', 'may', 'june', 'july', 'august', 'september', 'october', 'november',
'december')
jan feb mar apr may june july august september october november december
The element in the 5th position : june
july
Tuple before addition
(1, 2, 3, 4, 5)
Tuple after addition
(1, 2, 3, 4, 5, 7)
(1, 2, 3, 4, 5, 7, 'apple', 'orange', 'banana')
22
Tuple before change
('India', [10, 20, 30], 'USA')
Tuple after change
('India', [10, 20, 40], 'USA')

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

('mar', 'apr', 'may')


('may', 'june', 'july', 'august', 'september', 'october', 'november', 'december')
('jan', 'feb', 'mar', 'apr')
The position of 'october' in the tuple: 9

Result: The program was executed successfully and verified the output

Ex. No. : 7
Date:

Aim: To Write a program to demonstrate working with dictionaries in python.

Algorithm:
Begin
1. mon←{1:'jan',2:'feb',3:'mar',4:'apr',5:'may',6:'june'}
2. stud←{'kiran':23,'kumar':20,'dinesh':19,'rakesh':21}
3. write "mon Dictionary is ",str(mon))
4. write "The element in the key position 3 is :",mon[3])
5. write "The mon dictionary values are: ",mon.values())
6. write "The mon dictionary keys are: ",mon.keys())
7. #adding an item in the dictionary
8. write "Before addition"

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

9. for item in mon.values()


10. write item
11.mon[7]='july'
12.write "After addition"
13.for item in mon.values()
14. write item
15.write "Before deletion"
16.for item in stud.values()
17. write item
18.del stud['kumar']
19.write "After deletion"
20.for item in stud.values()
21. write item
22.write "Before change"
23.write "stud Dictionary is ",str(stud)
24.stud['dinesh']=55
25.write "Before change"
26.write "stud Dictionary is ",str(stud)
27.write "Key value pair of dictionary"
28.write stud.items()
End

Program:

mon={1:'jan',2:'feb',3:'mar',4:'apr',5:'may',6:'june'}
stud={'kiran':23,'kumar':20,'dinesh':19,'rakesh':21}

print("mon Dictionary is ",str(mon))


print("The element in the key position 3 is :",mon[3])
print("The mon dictionary values are: ",mon.values())
print("The mon dictionary keys are: ",mon.keys())

#adding an item in the dictionary


print("Before addition")

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

for item in mon.values():


print(item,end=' ')
mon[7]='july'
print()
print("After addition")
for item in mon.values():
print(item,end=' ')

print()
print("Before deletion")
for item in stud.values():
print(item,end=' ')
print()
del stud['kumar']

print("After deletion")
for item in stud.values():
print(item,end=' ')

print("Before change")
print("stud Dictionary is ",str(stud))
stud['dinesh']=55
print("Before change")
print("stud Dictionary is ",str(stud))

print("Key value pair of dictionary")


print(stud.items())

Output:

mon Dictionary is {1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr', 5: 'may', 6: 'june'}


The element in the key position 3 is : mar
The mon dictionary values are: dict_values(['jan', 'feb', 'mar', 'apr', 'may', 'june'])
The mon dictionary keys are: dict_keys([1, 2, 3, 4, 5, 6])
Before addition
jan feb mar apr may june
After addition
jan feb mar apr may june july
Before deletion

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

23 20 19 21
After deletion
23 19 21 Before change
stud Dictionary is {'kiran': 23, 'dinesh': 19, 'rakesh': 21}
Before change
stud Dictionary is {'kiran': 23, 'dinesh': 55, 'rakesh': 21}
Key value pair of dictionary
dict_items([('kiran', 23), ('dinesh', 55), ('rakesh', 21)])

Result: The program was executed successfully and verified the output

Ex. No. : 8
Date:

Aim: To write a python program to find largest of three numbers

Algorithm:

Begin
1. Read a,b,c

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

2. big ← a
3. if big<b then
4. big=b
5. If big<c then
6. big=c
7. Write big
End

Program:

num1 = float(input("Enter number 1: "))


num2 = float(input("Enter number 2: "))
num3 = float(input("Enter number 3: "))

big=num1

if (big<num2):
big=num2
if (big<num3):
big=num3

print("The Biggest number among the three is : ",big)

Output:

Enter number 1: 56
Enter number 2: 89
Enter number 3: 5
The Biggest number among the three is : 89.0

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Enter number 1: 100


Enter number 2: 3
Enter number 3: 78
The Biggest number among the three is : 100.0

Enter number 1: 5
Enter number 2: 80
Enter number 3: 234
The Biggest number among the three is : 234.0

Result: The program was executed successfully and verified the output

Ex. No. : 9
Date:

Aim: To write a Python program to convert temperatures to and from Celsius,


Fahrenheit. [Formula : c/5 = f-32/9]

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Algorithm:

1. Read c
2. Read f
3. f← 9/5*c+32
4. Write f
5. c←(f-32)*5/9
6. write c
End

Program:

# Convertion from celsius to Farenheit

celsius=int(input("Enter the temperature in celcius:"))


f=(celsius*1.8)+32
print("Temperature in farenheit is:",f)

# Convertion from Fahrenheit to Celsius

fahrenheit = int(input("Enter Temperature in Fahrenheit: "));


celsius = (fahrenheit-32)/1.8
print("Temperature in Celsius is =",celsius);

Output:

Enter the temperature in celcius:42


Temperature in farenheit is: 107.60000000000001
Enter Temperature in Fahrenheit: 104
Temperature in Celsius is = 40.0

Result: The program was executed successfully and verified the output

Ex. No. : 10
Date:

Aim: To Write a Python program to construct the following pattern, using a nested for

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

loop

Algorithm:

Begin
1. Read n
2. for i ←1 to n+1)
begin
3. for j ← 1 to i+1
4. begin
5. Write "*"
6. end
7. Write (“\n”)
8. end
9. for i←n to 1 step -1
begin
10. for j ←1 to i
begin
11. Write "*"
end
end
End

Program:

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

n=int(input("Enter n value : "))

for i in range(1,n+1):
for j in range(1,i+1):
print("*",end="")
print()
for i in range(n,1,-1):
for j in range(1,i):
print("*",end="")
print()

Output:

Enter n value : 5
*
**
***
****
*****
****
***
**
*

Enter n value : 8
*
**
***
****
*****
******
*******
********
*******
******
*****
****
***
**
*

Result: The program was executed successfully and verified the output

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Ex. No. : 11
Date:

Aim: To write a Python script that prints prime numbers less than n.

Algorithm:

Begin
1. Read r
2. for a in range(2,r+1)
begin
3. k←0
4. for i in range(2,a//2+1)
5. if(a%i==0)
6. k=k+1
7. if(k<=0)
8. Write a
end
End

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Program:

r=int(input("Enter upper limit: "))


for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a,end=' ')

#r=int(input("Enter upper limit: "))


#for val in range(2, r + 1):

# If num is divisible by any number


# between 2 and val, it is not prime

# for n in range(2, val):


# if (val % n) == 0:
# break
# else:
# print(val,end=' ')

Output:

Enter upper limit: 40


2 3 5 7 11 13 17 19 23 29 31 37

Enter upper limit: 100


2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
97

Enter upper limit: 20


2 3 5 7 11 13 17 19

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Result: The program was executed successfully and verified the output

Ex. No. : 12
Date:

Aim: To Write a python program to find factorial of a number using Recursion.

Algorithm:

Begin
1. Fact(n)
2. Begin
3. if n == 0 or 1 then
4. Return 1;
5. else
6. Return n*Call Fact(n-1);
7. endif
8. End
9. Read n
10.Write “Factorial of “,n,”is = “,Call Fact(n)
End

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Program:

def factorial(n):
if n == 1:
return n
else:
return n* factorial(n-1)

# take input from the user


num = int(input("Enter a number: "))

# check is the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is", factorial(num))

Output:

Enter a number: 5
The factorial of 5 is 120

Enter a number: 7
The factorial of 7 is 5040

Result: The program was executed successfully and verified the output

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Ex. No. : 13
Date:

Aim: Write a program that accepts the lengths of three sides of a triangle as inputs.
The program output should indicate whether or not the triangle is a right triangle

Algorithm:
Begin
1. Read s1,s2,s3
2. big←s1
3. if big<s2 then
4. big←s2
5. If big<s3
6. big←s3
7. if(big==s1) then
8. if(s1**2==(s2**2+s3**2)) then
9. Write "The triangle sides given is a right angled triangle”
10. else
11. Write "The triangle sides given is a not right angled triangle"
12.if(big==s2)
13. if(s2**2==(s1**2+s3**2)) then
14. Write "The triangle sides given is a right angled triangle”
15. else
16. Write "The triangle sides given is a not right angled triangle”
17.if(big==s3) then
18. if(s3**2==(s1**2+s2**2)) then
19. Write "The triangle sides given is a right angled triangle",
20. else:
21. print("The triangle sides given is a not right angled triangle”
End

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Program:

s1=int(input("Side 1 of the triangle "))


s2=int(input("Side 2 of the triangle "))
s3=int(input("Side 3 of the triangle "))

big=s1
if(big<s2):
big=s2
if(big<s3):
big=s3

if(big==s1):
if(s1**2==(s2**2+s3**2)):
print("The triangle sides given is a right angled triangle",s1**2,(s2**2+s3**2))
else:
print("The triangle sides given is a not right angled triangle",s1**2,
(s2**2+s3**2))
elif(big==s2):
if(s2**2==(s1**2+s3**2)):
print("The triangle sides given is a right angled triangle",s2**2,(s1**2+s3**2))
else:
print("The triangle sides given is a not right angled triangle", s2**2,
(s1**2+s3**2))
elif(big==s3):
if(s3**2==(s1**2+s2**2)):
print("The triangle sides given is a right angled triangle",s3**2,(s1**2+s2**2))
else:
print("The triangle sides given is a not right angled triangle", s3**2,
(s1**2+s2**2))

Output:

Side 1 of the triangle 4

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Side 2 of the triangle 5


Side 3 of the triangle 3
The triangle sides given is a right angled triangle 25 25

Side 1 of the triangle 6


Side 2 of the triangle 9
Side 3 of the triangle 3
The triangle sides given is a not right angled triangle 81 45

Result: The program was executed successfully and verified the output
Ex. No. : 14
Date:

Aim: To Write a python program to define a module to find Fibonacci Numbers and
import the module to another program.

Algorithm:

Begin
Load module fibo

1.
Read n
2.
Write "The fibonacci series is : "
3.
Call fibo.fib1(n)
4.
Read n
5.
Write "The fibonacci series is : "
6.
Res←Call fibo.fib2(n)
7.
for item in res
begin
8. Write item
end
End

Module file: fibo.py

1. function fib1(n)
begin
2. c←0,a←0,b←1
3. while c < n then
begin
4. write a

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

5. a←b, b←a+b,c←c+1
end

6. function fib2(n)
begin
7. result ← []
8. c←0
9. a←0, b ← 1
10.while c < n then
begin
11. result.append(a)
12. a←b, b←a+b,c← c+1
end
13.return result

Program:

import fibo

n=int(input("Enter n value : "))


print("The fibonacci series is : ")
fibo.fib1(n)

n=int(input("Enter n value : "))


print("The fibonacci series is : ")
res = fibo.fib2(n)

for item in res:


print(item,end=' ')

Module file: fibo.py

def fib1(n): # write Fibonacci series up to n


c=0
a, b = 0, 1
while c < n:
print(a, end=' ')
a, b,c = b, a+b,c+1
print()

def fib2(n): # return Fibonacci series up to n


result = []
c=0
a, b = 0, 1

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

while c < n:
result.append(a)
a, b,c = b, a+b,c+1
return result

Output:

Enter n value : 10
The fibonacci series is :
0 1 1 2 3 5 8 13 21 34
Enter n value : 20
The fibonacci series is :
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Result: The program was executed successfully and verified the output

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Ex. No. : 15
Date:

Aim: To write a python program to define a module and import a specific function in
that module to another program.

Algorithm:

Begin
from fibo load function fib2

1. Read n
2. Write "The fibonacci series is : "
3. Call fibo.fib1(n)
4. Read n
5. Write "The fibonacci series is : "
6. Res←Call fibo.fib2(n)
7. for item in res
8. begin
9. Write item
end
End

Module file: fibo.py

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

10.function fib1(n)
begin
11. c←0,a←0,b←1
12.while c < n then
begin
13. write a
14. a←b, b←a+b,c←c+1
end

15.function fib2(n)
begin
16. result ← []
17. c←0
18. a←0, b ← 1
19.while c < n then
begin
20. result.append(a)
21. a←b, b←a+b,c← c+1
end
22.return result
Program:

from fibo import fib2

n=int(input("Enter n value : "))


print("The fibonacci series is : ")
res = fib2(n)

for item in res:


print(item,end=' ')

Module file: fibo.py

def fib1(n): # write Fibonacci series up to n


c=0
a, b = 0, 1
while c < n:
print(a, end=' ')
a, b,c = b, a+b,c+1
print()

def fib2(n): # return Fibonacci series up to n


result = []

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

c=0
a, b = 0, 1
while c < n:
result.append(a)
a, b,c = b, a+b,c+1
return result

Output:

Enter n value : 7
The fibonacci series is :
0112358

Result: The program was executed successfully and verified the output

Ex. No. : 16
Date:

Aim: To write a script named copyfile.py. This script should prompt the user for the
names of two text files. The contents of the first file should be input and written
to the second file.

Algorithm:

Begin
1. Read fn1
2. Read fn2
3. Open fn1 for read mode with file handle fh1
4. Open fn2 for write mode with file handle fh2
5. for line in fh1
begin
6. fh2.write(line)
end
7. close files
End

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Program:

f1=input("Enter file name copy from : ")


f2=input("Enter file name copy to : ")

fh1=open(f1)
fh2=open(f2,"w")
for line in fh1:
fh2.write(line)
print(line)
fh1.close()
fh2.close()

Output:

intext.txt (input file content)

Hello to every one


Hello to python

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Good bye!

outtext.txt (output file content)

Hello to every one


Hello to python
Good bye!

Result: The program was executed successfully and verified the output

Ex. No. : 17
Date:

Aim: To write a program that inputs a text file. The program should print all of the
unique words in the file in alphabetical order.

Algorithm

Begin
1. Read fname
2. fh ← open fname for reading
3. lst = list()
4. for line in fh
5. word= line.rstrip().split()
6. for element in word
7. if element in lst then
8. continue
9. else

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

10. lst.append(element)
11.lst.sort()
12.for item in lst
13. write item
14.sortlst=sorted(lst, key=str.lower)
15.for item in sortlst
16. write item
End

Program:

fname = input("Enter file name: ")


fh = open(fname)
lst = list()
for line in fh:
word= line.rstrip().split()
for element in word:
if element in lst:
continue
else :
lst.append(element)
lst.sort()
for item in lst:
print(item,end=' ')
sortlst=sorted(lst, key=str.lower)

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

print()
for item in sortlst:
print(item,end=' ')

Output:

Enter file name: intext.txt


Good Hello bye! every one python to
bye! every Good Hello one python to

Result: The program was executed successfully and verified the output

Ex. No. : 18
Date:

Aim: To write a Python class to convert an integer to a roman numeral

Algorithm:

Begin

Load module sys

ROMAN_NUMERAL_TABLE ← [
("M", 1000), ("CM", 900), ("D", 500),
("CD", 400), ("C", 100), ("XC", 90),

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

("L", 50), ("XL", 40), ("X", 10),


("IX", 9), ("V", 5), ("IV", 4),
("I", 1)
]

1. function convert_to_roman(number)
2. begin
3. roman_numerals = []
4. for numeral, value in ROMAN_NUMERAL_TABLE:
5. while value <= number
6. begin
7. number -= value
8. roman_numerals.append(numeral)
9. End
10.return ' '.join(roman_numerals)
11.end

12.Read n

13.Write "The roman value of ",n,"is = ", call convert_to_roman(n)


End

Program:

import sys

ROMAN_NUMERAL_TABLE = [
("M", 1000), ("CM", 900), ("D", 500),
("CD", 400), ("C", 100), ("XC", 90),
("L", 50), ("XL", 40), ("X", 10),
("IX", 9), ("V", 5), ("IV", 4),
("I", 1)
]

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

def convert_to_roman(number):
roman_numerals = []
for numeral, value in ROMAN_NUMERAL_TABLE:
while value <= number:
number -= value
roman_numerals.append(numeral)

return ''.join(roman_numerals)

n=int(input("Enter a number: "))


print("The roman value of ",n,"is = ", convert_to_roman(n))

Output:

Enter a number: 65
The roman value of 65 is = LXV

Enter a number: 23
The roman value of 23 is = XXIII

Enter a number: 7754


The roman value of 7754 is = MMMMMMMDCCLIV

Enter a number: 11
The roman value of 11 is = XI

Result: The program was executed successfully and verified the output

Ex. No. : 19
Date:

Aim: To write a Python class to implement pow(x, n)

Algorithm:

Begin

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

1. class py_solution
2. begin
3. function pow(self, x, n)
4. begin
5. if x==0 or x==1 or n==1 then
6. return x
7. end
8. if x==-1 then
9. if n%2 ==0 then
10. return 1
11.else
12. return -1
13.if n==0 then
14. return 1
15.if n<0 then
16. return 1/call self.pow(x,-n)
17.val = call self.pow(x,n//2)
18.if n%2 ==0 then
19. return val*val
20.return val*val*x
21.while True then
22.begin
23. write "Enter q or Q to quit "
24. Read x
25. Read n
26. if (x=='q' or x=='Q') then
27. break
28. else
29. n=int(n)
30. x=int(x)
31. p=call py_solution().pow(x,n)
32. write x," to the power ",n," is = ",p
33. Continue
34.end
End

Program:

class py_solution:
def pow(self, x, n):
if x==0 or x==1 or n==1:
return x

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/self.pow(x,-n)
val = self.pow(x,n//2)
if n%2 ==0:
return val*val
return val*val*x

while True:
print("Enter q or Q to quit ")
x=input("Enter x value: ")
n=input("Enter n value: ")
if (x=='q' or x=='Q'):
break
else:
n=int(n)
x=int(x)
p=py_solution().pow(x,n)
print(x," to the power ",n," is = ",p)
print()
continue

Output:

Enter q or Q to quit
Enter x value: 2
Enter n value: 4

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

2 to the power 4 is = 16

Enter q or Q to quit
Enter x value: 5
Enter n value: 3
5 to the power 3 is = 125

Enter q or Q to quit
Enter x value: 4
Enter n value: -2
4 to the power -2 is = 0.0625

Enter q or Q to quit
Enter x value: 100
Enter n value: 0
100 to the power 0 is = 1

Enter q or Q to quit
Enter x value: q
Enter n value: q

Result: The program was executed successfully and verified the output

Ex. No. : 20
Date:

Aim: To write a Python class to reverse a string word by word.

Python Programming Laboratory Manual


Mahaveer Institute of Science and Technology

Algorithm:

Begin
1. class py_solution
2. begin
3. function reverse_words(self, s):
4. return ' '.join(reversed(s.split()))
5. end
6. Read s
7. rs=call py_solution().reverse_words(s)
8. write "The reversed sentence: ",rs
End

Program:

class py_solution:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))

s=input("Enter a string: ")


rs=py_solution().reverse_words(s)
print("The reversed sentence: ",rs

Output:

Enter a string: hello to every one


The reversed sentence: one every to hello

Result: The program was executed successfully and verified the output

Python Programming Laboratory Manual

You might also like