Pythonlabprgms (1 34)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

1.AIM: Write a program that asks the user for a weight in kilograms and converts it to pounds.

There are 2.2 pounds in


a kilogram.
Code:
kg=float(input("Enter the weight in kilograms:"))
#1kg=2.2pounds
p=kg*2.2
print("{} kgs in pounds is {}".format(kg,p))
output:
Enter the weight in kilograms:12.54
12.54 kgs in pounds is 27.588

2.AIM: Write a program that asks the user to enter three numbers(use 3 separate input statements).Create variables
called total and average that holds the sum and average of the three numbers and print out the values of total and
average.
Code:
a=int(input("enter the first number:"))
b=int(input("enter the second number:"))
c=int(input("enter the third number:"))
total=a+b+c
average=total/3
print("sum of %d,%d and %d is %d"%(a,b,c,total))
print("avg of %d,%d and %d is %f"%(a,b,c,average))
output:
enter the first number:27
enter the second number:32
enter the third number:37
sum of 27,32 and 37 is 96
avg of 27,32 and 37 is 32.000000

3.Aim: Write a program that uses a „for‟ loop to print the numbers 8,11,14,17,20,……..,83,86,89.
Code(1):
for i in range(8,90,3):
print(i,end=" ")
output:
8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89

Code(2):
for i in range(8,87,3):
print(i,end=",")
print(89)
output:
8,11,14,17,20,23,26,29,32,35,38,41,44,47,50,53,56,59,62,65,68,71,74,77,80,83,86,89
Code(3):
for i in range(8,90,3):
if(i=='89'):
print(89)
else:
print(i,end=",")
output:
8,11,14,17,20,23,26,29,32,35,38,41,44,47,50,53,56,59,62,65,68,71,74,77,80,83,86,89

4. Aim: Write a program that asks the user for their name and how many times to print it. The program should print
out the user‟s name the specified number of times.
Code:
name=input("Enter your name:")
a=int(input("Enter the number of times to print your name:"))
for i in range(0,a):
print("Your name is %s"%name)
output:
Enter your name:Python
Enter the number of times to print your name:5
Your name is Python
Your name is Python
Your name is Python
Your name is Python
Your name is Python

5. Aim: Use a „for‟ loop to print a triangle like the one below. Allow the user to specify how high the triangle should
be
*
* *
* * *
* * * *
Code:
n=int(input("enter the height of the triangle:"))
for i in range(1,n+1):
print("* "*i)
output:
enter the height of the triangle:5
*
**
***
****
* * * **

6. Aim: Generate a random number between 1 and 10. Ask the user to guess the number and print a message based on
whether they get it right or not.
Code:
import random
x=random.randint(1,10)
y=int(input("guess the number between 1 and 10:"))
print("The random number is %d"%x)
if(x==y):
print("guess is correct")
else:
print("guess is wrong")
output:
guess the number between 1 and 10:7
The random number is 5
guess is wrong

7. Aim: Write a program that asks the user for two numbers and prints „close‟ if the numbers are within .001 of each
other and not close otherwise.
Code:
a=float(input("enter the first number:"))
b=float(input("enter the second number:"))
if abs(a-b)<0.001:
print("close")
else:
print("not close")
Output:
enter the first number:25.00
enter the second number:25.01
not close

8. Aim: Write a program that asks the user to enter a word and prints out whether that word contains any vowels.
Code(1):
w=input("enter the word:")
v=('a','e','i','o','u')
if any(i for i in w if i in v):
print("The word '{}' contains vowels".format(w))
else:
print("The word '{}' doesn't contains vowels".format(w))
Output:
enter the word:chennai
The word 'chennai' contains vowels
Code(2):
w=input("enter the word:")
v="aeiouAEIOU"
if (len([i for i in w if i in v])!=0):
print("The word '{}' contains vowels".format(w))
else:
print("The word '{}' doesn't contains vowels".format(w))
Output:
enter the word:python
The word 'python' contains vowels
Code(3):
w=input("enter the word:")
if (set('aeiou').intersection(w.lower())):
print("The word '{}' contains vowels".format(w))
else:
print("The word '{}' doesn't contains vowels".format(w))
Output:
enter the word:orange
The word 'orange' contains vowels

9. Aim: Write a program that asks the user to enter two strings of the same length. The program should then check to
see if the strings are of the same length. If they are not, the program should print an appropriate message and exit. If
they are of the same length, the program should alternate the characters of two strings. For example, if the user enters
abcde and ABCDE the program should print out AaBbCcDdEe
Code:
a=input("Enter the two strings of same length.\nEnter the first string:")
b=input("Enter the second string:")
if(len(a)!=len(b)):
print("The strings %s and %s are not of same lengths"%(a,b))
else:
print("The strings %s and %s are equal with same lengths"%(a,b))
for i in range(0,len(b)):
print(a[i]+b[i],end='')
Output(1):
Enter the two strings of same length.
Enter the first string:Happy
Enter the second string:hello
The strings happy and hello are equal with same lengths
Hhaeplplyo
Output(2):
Enter the two strings of same length.
Enter the first string:cat
Enter the second string:lion
The strings cat and lion are not of same lengths

10. Aim: Write a program that asks the user for a large integer and inserts commas into it according to the standard
American convention for commas in large numbers. For instance, if the user enters 1000000, the output should be
1,000,000.
Code:
n=int(input("enter the number:"))
print("{:,}".format(n))
Output:
enter the number:1234567
1,234,567

11. Aim: In algebraic expressions, the symbol for multiplication is often left out, as in 3x+4y or 3(x+5). Computers
prefer those expressions to include the multiplication symbol, like 3*x+4*y or 3*(x+5). Write a program that asks the
user for an algebraic expression and then inserts multiplication symbols were appropriate.
Code:
a=input("enter an expression:")
s=a[0]
for i in range(1,len(a)):
if(a[i].isalpha() and a[i-1].isdigit() or a[i]=='(' or a[i].isalpha() and a[i-1].isalpha() or a[i-1]==')' or
a[i].isdigit() and a[i-1].isalpha()):
s=s+"*"
s=s+a[i]
print("expression is %s"%(s))
Output(1):
enter an expression:(a+b)c
expression is (a+b)*c
Output(2):
enter an expression:(ab)c3+4
expression is (a*b)*c*3+4

12. Aim: Write a program that generates a list of 20 random numbers between 1 and 100.
(a). Print the list
(b). Print the average of the elements in the list
(c). Print the largest and smallest values in the list
(d). Print the second largest and second smallest entries in the list
(e). Print how many even numbers are in the list.
Code(a):
from random import randint
a=[]
for i in range(20):
a.append(randint(1,100))
print("list is",a)
Output:
list is [55, 80, 72, 13, 61, 49, 5, 42, 35, 77, 62, 18, 7, 12, 65, 31, 94, 8, 82, 81]
Code(b):
from random import randint
import statistics
a=[]
for i in range(20):
a.append(randint(1,100))
print("list is",a)
print("Average of elements in the list is %d"%(statistics.mean(a))) #sum(a)/len(a)
Output:
list is [7, 87, 65, 18, 34, 18, 89, 84, 4, 57, 33, 38, 33, 54, 21, 6, 39, 32, 23, 62]
Average of elements in the list is 40
Code(c):
from random import randint
a=[]
for i in range(20):
a.append(randint(1,100))
print("list is",a)
print("Largest and Smallest values in the list is %d and %d"%(max(a),min(a)))
Output:
list is [35, 63, 76, 92, 32, 76, 1, 89, 56, 58, 55, 64, 17, 3, 61, 79, 35, 8, 90, 48]
Largest and Smallest values in the list is 92 and 1
Code(d):
from random import randint
a=[]
for i in range(20):
a.append(randint(1,100))
a.sort()
print(“list is”,a)
print("Second largest&second smallest entries in the list is %d and %d"%(a[-2],a[1]))
Output:
list is [9, 17, 18, 20, 20, 23, 31, 38, 48, 53, 56, 56, 59, 61, 72, 74, 80, 86, 96, 97]
Second largest&second smallest entries in the list is 96 and 17
Code(e):
from random import randint
a=[]
count=0
for i in range(20):
a.append(randint(1,100))
if(a[i]%2==0):
count+=1
print("list is",a)
print("The number of Even numbers in the list are %d"%(count))
Output:
list is [100, 86, 13, 18, 53, 38, 93, 61, 72, 27, 91, 88, 86, 45, 57, 86, 6, 28, 3, 32]
The number of Even numbers in the list are 11

13. AIM: Write a program that asks the user for an integer and creates a list that contains of the factors of that
integers.
CODE 1:
n=int(input("Enter any integer:"))
a=[i for i in range(1,n+1) if n%i==0] #using list comprehension
print("Factors of {} in the list are {}".format(n,a))
OUTPUT 1:
Enter any integer:14
Factors of 14 in the list are [1, 2, 7, 14]
CODE 2:
n=int(input("Enter any integer:"))
a=[]
for i in range(1,n+1): #not using list comprehension
if n%i==0:
a.append(i)
print("Factors of {} in the list are {}".format(n,a))
OUTPUT 2:
Enter any integer:16
Factors of 16 in the list are [1, 2, 4, 8, 16]

14. AIM:Write a program that generates 100 random integers that are either 0 or 1. Then find the longest run
of zeroes, the largest number of zeros in a row.
CODE:
import random as r
l=[];count=0
n=int(input("Enter the number of random numbers you want to print:"))
for i in range(n):
l.append(r.randint(0,1))
if(l[i]==0):
count+=1
print("Largest run of zeros is %d"%(count))
print("Longest run of zeros is",len(max("".join(map(str,l))).split(",")))
print(l)
OUPUT:
Enter the number of random numbers you want to print:10
Largest run of zeros is 3
Longest run of zeros is 1
[1, 1, 1, 1, 0, 1, 0, 1, 0, 1]

15. AIM:Write a program that removes any repeated items from a list so that each item appears at most once.
CODE:
a=[int(i) for i in input("Enter elements into list seperated by space:").split(' ')]
b=[]
for i in a:
if i not in b:
b.append(i)
print("List after deleting repeated elements",b)
OUTPUT:
Enter elements into list seperated by space:1 2 3 4 5 4 6 8 1
List after deleting repeated elements [1, 2, 3, 4, 5, 6, 8]

16. AIM:Write a program that asks the user to enter a length in feet. The program should then give the user
the option to convert from feet into inches, yards, miles, millimeters, centimeters, meters or kilometers.
CODE:
a=float(input("Enter length in feet:"))
print("1.Inches\n2.Yards\n3.Miles\n4.Millimeters\n5.Centimeters\n6.Meters\n7.Kilometers")
opt=int(input("Enter your choice:"))
if opt==1:
print("{} feet is equal to {} inches".format(a,a*12))
elif opt==2:
print("{} feet is equal to {} yards".format(a,a/3))
elif opt==3:
print("{} feet is equal to {} miles".format(a,a/5280))
elif opt==4:
print("{} feet is equal to {} millimeters".format(a,a*304.8))
elif opt==5:
print("{} feet is equal to {} centimeters".format(a,a*30.48))
elif opt==6:
print("{} feet is equal to {} meters".format(a,a*3.048))
elif opt==7:
print("{} feet is equal to {} kilometers".format(a,a*0.0003048))
else:
print("Please enter valid option")
OUTPUT:
Enter length in feet:10
1.Inches
2.Yards
3.Miles
4.Millimeters
5.Centimeters
6.Meters
7.Kilometers
Enter your choice:2
10.0 feet is equal to 3.3333333333333335 yards

17. AIM:Write a function called sum_digits that is given an integer number and returns sum of the digits of
number.
CODE:
def sum_digits(num):
s=0
while(num>0):
s+=num%10
num=num//10
print(s)
a=int(input("Enter a number:"))
sum_digits(a)
OUTPUT:
Enter a number:153
9

18. AIM:Write a function called first_diff that is given two strings and returns the first location in which the
strings differ. If the strings are identical, it should return –1.
CODE:
str1,str2=input("Enter first string:"),input("Enter second string:")
def first_diff(a,b):
if(len(a)==len(b)):
for i in range(max(len(a),len(b))):
if a[i]!=b[i]:
return i+1
return -1
else:
for i in range(min(len(a),len(b))):
if a[i]!=b[i]:
return i+1
return i+1
n=first_diff(str1,str2)
if n==-1:
print("Given strings are Identical")
else:
print("Given strings differ at position %d"%(n))
OUTPUT:
Enter first string:arsha
Enter second string:harsha
Given strings differ at position 1

19. AIM:Write a function called number_of_factors that takes an integers and returns how many factors that
number has.
CODE:
a=int(input("Enter an integer:"))
def fact_of_num(num):
return (len([i for i in range(1,num+1) if num%i==0]),list(i for i in range(1,num+1) if num%i==0))
l,c=fact_of_num(a)
print("The number %d has %d factors"%(a,l))
print("The factors are:")
for i in c:
print(i)
OUTPUT:
Enter an integer:36
The number 36 has 9 factors
The factors are:
1
2
3
4
6
9
12
18
36

20. AIM:Write a function called is_sorted that is given a list and return True if the list is sorted and False
otherwise.
CODE:
a=[int(i) for i in input("Enter values separated by comma:").split(",")]
def is_sorted(a):
if all(a[i+1]>a[i] for i in range(len(a)-1)):
return True
else:
return False
print(is_sorted(a))
OUTPUT:
Enter values separated by comma:1,2,3,4,5,3
False
21. AIM:Write a function called root that is given a number x and an integer n and return x power(1/n). In the
function definition, set the default value n=2.
CODE 1:
def root(x,n=2):
return (x**1/n)
x=float(input("Enter the base value:"))
n=eval(input("Enter the power value:"))
print("%f to the power of 1/%d is %f"%(x,n,root(x,n)))
OUTPUT 1:
Enter the base value:9.5
Enter the power value:3
9.500000 to the power of 1/3 is 3.166667
CODE 2:
def root(x,n=2):
return pow(x,(1/n))
x=float(input("Enter the base value:"))
print("%f to the power of 1/2 is %f "%(x,root(x)))
OUTPUT 2:
Enter the base value:5.5
5.500000 to the power of 1/2 is 2.345208

22. AIM:Write a function called primes that is given a number and returns a list of first n primes. Let the
default value of n be 100.
CODE:
def primes(n=100):
x=2;a=[];y=0
while(y<n):
p=0
for i in range(2,x):
if x%i==0:
p=1
if p==0:
a.append(x)
y+=1
x+=1
return a
n=int(input("Enter number of primes:"))
print("list of first {} primes is {}".format(n,primes(n)))
print("list of first 100 primes is {}".format(primes()))
OUTPUT:
Enter number of primes:20
list of first 20 primes is [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
list of first 100 primes is [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, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337,
347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541]

23.AIM:Write a function called merge that takes two already sorted lists of possibly different length and
merges them into a single sorted list.
(a) Do this using sort() method
CODE 1(a):
l1=[int(i) for i in input("Enter numbers seperated by comma:").split(",")]
l2=[int(i) for i in input("Enter numbers seperated by comma:").split(",")]
def merge():
l=l1+l2
l.sort()
print("Sorted list is",l)
merge()
OUTPUT 1(a):
Enter numbers seperated by comma:1,2,3
Enter numbers seperated by comma:1,2,3
Sorted list is [1, 1, 2, 2, 3, 3]
CODE 2(a):
from heapq import merge #pip install heapq
l1=[int(i) for i in input("Enter numbers seperated by comma:").split(",")]
l2=[int(i) for i in input("Enter numbers seperated by comma:").split(",")]
l=list(merge(l1,l2))
print("Sorted list is ",l)
OUTPUT 2(a):
Enter numbers seperated by comma:1,2,3
Enter numbers seperated by comma:0,1,2
Sorted list is [0, 1, 1, 2, 2, 3]
(b) Do this without using the sort() method
CODE 1(b):
def merge(l1,l2):
l=l1+l2
for i in range(0,len(l)-1):
for j in range(0,i):
if(l[j]>l[i]):
l[i],l[j]=l[j],l[i]
print("Merged list in sorted order is",l)
l1=[int(i) for i in input("Enter numbers separated by comma:").split(",")]
l2=[int(i) for i in input("Enter numbers separated by comma:").split(",")]
merge(l1,l2)
OUTPUT 1(b):
Enter numbers separated by comma:1,2,3
Enter numbers separated by comma:1,3,5
Merged list in sorted order is [1, 1, 2, 3, 3, 5]
CODE 2(b):
l1=[int(i) for i in input("Enter numbers seperated by comma:").split(",")]
l2=[int(i) for i in input("Enter numbers seperated by comma:").split(",")]
b,i,j=[],0,0
while(i<len(l1) and j<len(l2)):
if l1[i]<l2[j]:
b.append(l1[i])
i+=1
else:
b.append(l2[j])
j+=1
b=b+l1[i:]+l2[j:]
print("The combined sorted list is - "+str(b))
OUTPUT 2(b):
Enter numbers separated by comma:1,2,3
Enter numbers separated by comma:2,3,4
The combined sorted list is - [1, 2, 2, 3, 3, 4]
24. AIM:Write a program that asks the user for a word and finds all the smaller words that can be made from
the letters of that words. The number of occurrences of a letter in smaller word cannot exceed the number of
occurrences of the letter in user's word.
CODE:
from itertools import permutations #pip install itertools
import enchant #pip install pyenchant
d=enchant.Dict("en_US")
output,inp=set(),input("Enter a word:")
letter=[x.lower() for x in inp]
for n in range(2,len(inp)):
for y in list(permutations(letter,n)):
z="".join(y)
if d.check(z):
output.add(z)
print(output)
OUTPUT:
Enter a word: python
{'ht', 'phony', 'on', 'hon', 'pho', 'pt', 'typ', 'tony', 'hop', 'ton', 'top', 'thy', 'ho', 'yo', 'hypo', 'typo', 'tho', 'op', 'phon',
'to', 'oh', 'toy', 'hp', 'hoy', 'opt', 'phot', 'pot', 'tn', 'not', 'hot', 'hyp', 'yon', 'pony', 'nth', 'no'}

25) AIM:Write a program that asks the user for a word and finds all the smaller words that can be made from
the letters of that word. The number of occurrences of a letter in a smaller word can’t exceed the number of
occurrences of the letter in the user’s word.
CODE:
for i in open('email.txt').readlines():
print(i.replace('\n',';'),end="")
INPUT FILE:
[email protected]
[email protected]
[email protected]
[email protected]
OUTPUT:
[email protected];[email protected];[email protected];[email protected];
26)AIM: Write a program that reads a list of temperatures from a file called temps.txt, converts those
temperatures to Fahrenheit, and writes the results to a file called ftemps.txt.
CODE:
f1=open("temps.txt",'r')
with open("ftemps.txt",'w') as f2:
for i in f1.read().split():
f2.write(str((float(i)*9/5)+32)+"\n")
#f2.write(str(((float(i)-273)*(9/5))+32)+"\n")
f1.close()
f2.close()
INPUT FILE: temps.txt
45
45.5
54
34.4
OUTPUT FILE: ftemps.txt
113.0
113.9
129.2
93.91999999999999
27)AIM: Write a class called Product. The class should have fields called name, amount, and price,holding the
product’s name, the number of items of that product in stock, and the regularprice of the product. There
should be a method get_price that receives the number of itemsto be bought and returns a the cost of buying
that many items, where the regular price ischarged for orders of less than 10 items, a 10% discount is applied
for orders of between10 and 99 items, and a 20% discount is applied for orders of 100 or more items.
Thereshould also be a method called make_purchase that receives the number of items to bebought and
decreases amount by that much.
CODE:
class Product:
def __init__(self, name, amount, price):
self.name = name
self.amount = amount
self.price = price
def get_price(self, number_to_be_bought):
discount = 0
if number_to_be_bought < 10:
pass
elif 10 <= number_to_be_bought < 99:
discount = 10
else:
discount = 20
price = (100 - discount) / 100 * self.price
return price * number_to_be_bought
def make_purchase(self, quantity):
self.amount -= quantity
name, amount, price = 'oppo', 200, 19000
oppo = Product(name, amount, price)

# name = input('name:')
# amount = int(input('Digit amount of items'))
# price = int(input('Digit price of items'))

name, amount, price = 'oppo', 200, 19000


oppo = Product(name, amount, price)
# quantity = int(input('Digit amount of items to buy'))

q1 = 4
print(f'cost for {q1} {oppo.name} = {oppo.get_price(q1)}')
oppo.make_purchase(q1)
print(f'remaining stock: {oppo.amount}\n')

q2 = 12
print(f'cost for {q2} {oppo.name} = {oppo.get_price(q2)}')
oppo.make_purchase(q2)
print(f'remaining stock: {oppo.amount}\n')

q3 = 112
print(f'cost for {q3} {oppo.name} = {oppo.get_price(q3)}')
oppo.make_purchase(q3)
print(f'remaining stock: {oppo.amount}\n')
OUTPUT:
cost for 4 oppo = 76000.0
remaining stock: 196
cost for 12 oppo = 205200.0
remaining stock: 184
cost for 112 oppo = 1702400.0
remaining stock: 72

28)AIM: Write a class called Time whose only field is a time in seconds. It should have a method called
convert_to_minutes that returns a string of minutes and seconds formatted as in the following example: if
seconds is 230, the method should return '5:50'. It should also have a method called convert_to_hours that
returns a string of hours, minutes, and seconds formatted analogously to the previous method.
CODE:
class Time:
def __init__(self,time):
self.time=time
def convert_to_minutes(self):
return '{}:{}'.format(self.time//60,self.time%60)
def convert_to_hours(self):
t=self.time % (24 * 3600)
hour=t//3600
t%=3600
minutes=t//60
t%=60
return '{}:{}:{}'.format(hour,minutes,t)
a=Time(5400)
print(a.convert_to_minutes())
print(a.convert_to_hours())
OUTPUT:
90:0
1:30:0

29) AIM:Write a class called Converter. The user will pass a length and a unit when declaring an object from
the class—for example, c = Converter(9,'inches'). The possible units are inches, feet, yards, miles, kilometers,
meters, centimeters, and millimeters. For each of these units there should be a method that returns the length
converted into those units. For example, using the Converter object created above, the user could call c.feet()
and should get 0.75 as the result.
CODE:
from unit_convert import UnitConvert #pip install unit_convert
class Converter:
def __init__(self,l,u):
self.l=l
self.u=u
def feet(self):
if self.u=="inches":
print(UnitConvert(inches=self.l).feet)
elif self.u=="yards":
print(UnitConvert(yards=self.l).feet)
elif self.u=="miles":
print(UnitConvert(miles=self.l).feet)
elif self.u=="kilometers":
print(UnitConvert(km=self.l).feet)
elif self.u=="meters":
print(UnitConvert(m=self.l).feet)
elif self.u=="centimeters":
print(UnitConvert(cm=self.l).feet)
elif self.u=="millimeters":
print(UnitConvert(mm=self.l).feet)
def inches(self):
if self.u=="feet":
print(UnitConvert(feet=self.l).inches)
elif self.u=="yards":
print(UnitConvert(yards=self.l).inches)
elif self.u=="miles":
print(UnitConvert(miles=self.l).inches)
elif self.u=="kilometers":
print(UnitConvert(km=self.l).inches)
elif self.u=="meters":
print(UnitConvert(m=self.l).inches)
elif self.u=="centimeters":
print(UnitConvert(cm=self.l).inches)
elif self.u=="millimeters":
print(UnitConvert(mm=self.l).inches)
def yards(self):
if self.u=="inches":
print(UnitConvert(inches=self.l).yards)
elif self.u=="feet":
print(UnitConvert(feet=self.l).yards)
elif self.u=="miles":
print(UnitConvert(miles=self.l).yards)
elif self.u=="kilometers":
print(UnitConvert(km=self.l).yards)
elif self.u=="meters":
print(UnitConvert(m=self.l).yards)
elif self.u=="centimeters":
print(UnitConvert(cm=self.l).yards)
elif self.u=="millimeters":
print(UnitConvert(mm=self.l).yards)
def miles(self):
if self.u=="inches":
print(UnitConvert(inches=self.l).miles)
elif self.u=="yards":
print(UnitConvert(yards=self.l).miles)
elif self.u=="feet":
print(UnitConvert(feet=self.l).miles)
elif self.u=="kilometers":
print(UnitConvert(km=self.l).miles)
elif self.u=="meters":
print(UnitConvert(m=self.l).miles)
elif self.u=="centimeters":
print(UnitConvert(cm=self.l).miles)
elif self.u=="millimeters":
print(UnitConvert(mm=self.l).miles)
def kilometers(self):
if self.u=="inches":
print(UnitConvert(inches=self.l).km)
elif self.u=="yards":
print(UnitConvert(yards=self.l).km)
elif self.u=="miles":
print(UnitConvert(miles=self.l).km)
elif self.u=="feet":
print(UnitConvert(feet=self.l).km)
elif self.u=="meters":
print(UnitConvert(m=self.l).km)
elif self.u=="centimeters":
print(UnitConvert(cm=self.l).km)
elif self.u=="millimeters":
print(UnitConvert(mm=self.l).km)
def meters(self):
if self.u=="inches":
print(UnitConvert(inches=self.l).m)
elif self.u=="yards":
print(UnitConvert(yards=self.l).m)
elif self.u=="miles":
print(UnitConvert(miles=self.l).m)
elif self.u=="kilometers":
print(UnitConvert(km=self.l).m)
elif self.u=="feet":
print(UnitConvert(feet=self.l).m)
elif self.u=="centimeters":
print(UnitConvert(cm=self.l).m)
elif self.u=="millimeters":
print(UnitConvert(mm=self.l).m)
def centimeters(self):
if self.u=="inches":
print(UnitConvert(inches=self.l).cm)
elif self.u=="yards":
print(UnitConvert(yards=self.l).cm)
elif self.u=="miles":
print(UnitConvert(miles=self.l).cm)
elif self.u=="kilometers":
print(UnitConvert(km=self.l).cm)
elif self.u=="meters":
print(UnitConvert(m=self.l).cm)
elif self.u=="feet":
print(UnitConvert(feet=self.l).cm)
elif self.u=="millimeters":
print(UnitConvert(mm=self.l).cm)
def millimeters(self):
if self.u=="inches":
print(UnitConvert(inches=self.l).mm)
elif self.u=="yards":
print(UnitConvert(yards=self.l).mm)
elif self.u=="miles":
print(UnitConvert(miles=self.l).mm)
elif self.u=="kilometers":
print(UnitConvert(km=self.l).mm)
elif self.u=="meters":
print(UnitConvert(m=self.l).mm)
elif self.u=="centimeters":
print(UnitConvert(cm=self.l).mm)
elif self.u=="feet":
print(UnitConvert(feet=self.l).mm)
c=Converter(1,'feet')
c.inches()
c.yards()
c.miles()
c.kilometers()
c.meters()
c.centimeters()
c.millimeters()
OUTPUT:
12.000000000000002
0.33333333333333337
0.0001893944101308611
0.00030480000000000004
0.3048
30.48
304.8

30) AIM:Write a Python class to implement pow(x, n).


CODE:
class py_solution:
def pow(self, x, n):
if x==0 or x==1 or n==1:
return x
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)
print(n)
print(val)
if n%2 ==0:
return val*val
return val*val*x
#print(py_solution().pow(2, -3))
print(py_solution().pow(3,7))
#print(py_solution().pow(100, 0))

"""
def power(x, y):

if(y == 0): return 1


temp = power(x, int(y / 2))

if (y % 2 == 0):
return temp * temp
else:
if(y > 0): return x * temp * temp
else: return (temp * temp) / x

# Driver Code
x, y = 2, -3
print('%.6f' %(power(x, y))) """
OUTPUT:
0.125
243
1

31) AIM:Write a Python class to reverse a string word by word.


CODE:
class revstr:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))
print(revstr().reverse_words('Hello Python'))
"""
def reverse_string_words(text):
for line in text.split('\n'):
return(' '.join(line.split()[::-1]))
print(reverse_string_words("Python is fun"))
print(reverse_string_words("Python Programming"))
"""
OUTPUT:
Python Hello

32) AIM:Write a program that opens a file dialog that allows you to select a text file. The program
then displays the contents of the file in a textbox.
CODE:
from tkinter import *
from tkinter.filedialog import *
from tkinter.scrolledtext import ScrolledText
root = Tk()
root.title('File dialog')
filename=askopenfilename(initialdir='/',filetypes=[('All files', '.*'),('All files', '*')])
s=open(filename).read()
textbox = ScrolledText()
textbox.grid()
textbox.insert(1.0,s)
mainloop()
OUTPUT:

33)AIM: Write a program to demonstrate Try/except/else.


CODE:
def divide(x,y):
try:
result=x//y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Your answer is :{}".format(result))
"""finally:
print('This is always executed') """
divide(3,2)
divide(3,0)
OUTPUT:
Your answer is :1
Sorry ! You are dividing by zero

34)AIM: Write a program to demonstrate try/finally and with/as.


CODE:
data=input("Enter the data you want to store in a file:")
try:
with open('example.txt', 'w') as f:
f.write(data)
finally:
print("Your data is successfully stored in a file")
OUTPUT:
Enter the data you want to store in a file:PYTHON
Python Hello
Your data is successfully stored in a file

You might also like