Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Python Lab Manaual

The document is a Python lab manual for first-year Computer Science and Engineering students, detailing course objectives, outcomes, and a list of programming experiments. It emphasizes hands-on experience in Python programming, covering topics such as data types, loops, functions, and object-oriented programming. The manual also includes a series of coding exercises designed to reinforce the concepts learned in the course.

Uploaded by

HODCSE RKCE
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

Python Lab Manaual

The document is a Python lab manual for first-year Computer Science and Engineering students, detailing course objectives, outcomes, and a list of programming experiments. It emphasizes hands-on experience in Python programming, covering topics such as data types, loops, functions, and object-oriented programming. The manual also includes a series of coding exercises designed to reinforce the concepts learned in the course.

Uploaded by

HODCSE RKCE
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/ 28

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PYTHONLAB MANUAL

Class: I Year II Semester (CSE)

Branch: Computer Science and Engineering

Prepared By: SHABAAZ SHAIK

Academic Year: 2022-23

Regulation: R20
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VISION

To become a prominent knowledge hub for learners, strive for education excellent with
innovative and industrial techniques so as to meet the global needs.

MISSON

To provide hands-on-experience and problem-solving skills by imparting


DM1
quality education.

To impart quality education with professional and personal ethics, so as to


DM2
meet the challenging global needs of the industry and society.

To provide academic infrastructure and develop linkage with the world


DM3
class organizations to strengthen industry-academia relationship for learners.

To impart project management skills with an attitude for life-long learning


DM4
with ethical values.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LIST OF PEOs

Engage in designing, implementing, operating and maintain systems in the field of


PE01 computer science and engineering and allied engineering industries.

Solve the problems of social relevance applying the knowledge of computer


PE02
science and engineering and pursue higher education and research
PE03 Work effectively as individuals and as team members in multidisciplinary projects

Engage in lifelong learning, career enhancement and adopt to changing


PE04
professional and societal needs

List of PSOs

Analyze and develop computer programs in the areas related to system software,
multimedia, web design and networking for efficient design of computer based
PSO1
system of varying complexity basic engineering sciences and Computer
fundamentals.

To apply standard practices and strategies in software project development using


PSO2 open ended programming environments to deliver a quality product for business
success.

Implement and design various models in real time systems.


PSO3
Course Objectives:
The Objectives of Python Programming are
 To learn about Python programming language syntax, semantics, and the runtime
environment
 To be familiarized with universal computer programming concepts like data types,
containers
 To be familiarized with general computer programming concepts like conditional
execution, loops & functions
 To be familiarized with general coding techniques and object-oriented programming
Course Outcomes:
 Develop essential programming skills in computer programming concepts like data
types, containers
 Apply the basics of programming in the Python language
 Solve coding tasks related conditional execution, loops
 Solve coding tasks related to the fundamental notions and techniques used in
objectoriented programming
Minimum System requirements:
 Processors: Intel Atom® processor or Intel® Core™ i3 processor.
 Disk space: 1 GB.
 Operating systems: Windows* 7 or later
 IDLE
About lab:
Python is a general purpose, high-level programming language; other high level languages
you might have heard of C++, PHP, Java and Python. Virtually all modern programming
languages make us of an Integrated Development Environment (IDE), which allows the
creation, editing, testing, and saving of programs and modules. In Python, the IDE is called
IDLE (like many items in the language, this is a reference to the British comedy group
Monty Python, and in this case, one of its members, Eric Idle).
Many modern languages use both processes. They are first compiled into a lower level
language, called byte code, and then interpreted by a program called a virtual machine.
Python uses both processes, but because of the way programmers interact with it, it is
usually considered an interpreted language.

CONTENTS

S.No Experiment Page Nos


1 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
2 Write a program that asks the user to enter three numbers
(use three separate input statements). Create variables
called total and average that hold the sum and average of
the three numbers and print out the values of total and
average.
3 Write a program that uses a for loop to print the numbers
8, 11, 14, 17, 20, . . . , 83, 86, 89.
4 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
5 Use a for loop to print a triangle like the one below.
Allow the user to specify how high the triangle should be.
*
**
***
****
6 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
7 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.
8 Write a program that asks the user to enter a word and
prints out whether that word contains any vowels
9 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 the two strings. For example, if the user
enters abcde and ABCDE the program should print out
AaBbCcDdEe
10 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
11 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 where appropriate.
12 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
13 Write a program that asks the user for an integer and
creates a list that consists of the factors of that integer.
14 Write a program that generates 100 random integers that
are either 0 or 1. Then find the longest run of zeros, the
largest number of zeros in a row. For instance, the longest
run of zeros in [1,0,1,1,0,0,0,0,1,0,0] is 4.
15 Write a program that removes any repeated items from a
list so that each item appears at most once. For instance,
the list [1,1,2,3,4,3,0,0] would become [1,2,3,4,0]
16 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. Say if the user enters a
1, then the program converts to inches, if they enter a 2,
then the program converts to yards, etc. While this can be
done with if statements,it is much shorter with lists and it
is also easier to add new conversions if you use lists.
17 Write a function called sum_digits that is given an integer
num and returns the sum of the digits of num.
18 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.
19 Write a function called number_of_factors that takes an
integer and returns how many factors the number has.
20 Write a function called is_sorted that is given a list and
returns True if the list is sorted and False otherwise.
21 Write a function called root that is given a number x and
an integer n and returns x1/n . In the function definition,
set the default value of n to 2
22 Write a function called primes that is given a number n
and returns a list of the first n primes. Let the default
value of n be 100
23 Write a function called merge that takes two already
sorted lists of possibly different lengths, and merges them
into a single sorted list
24 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.
25 Write a program that reads a file consisting of email
addresses, each on its own line. Your program should
print out a string consisting of those email addresses
separated by semicolons.
26 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.
27 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 regular price of the product. There should be a
method get_price that receives the number of items to be
bought and returns a the cost of buying that many items,
where the regular price is charged for orders of less than
10 items, a 10% discount is applied for orders of between
10 and 99 items, and a 20% discount is applied for orders
of 100 or more items. There should also be a method
called make_purchase that receives the number of items
to be bought and decreases amount by that much.
28 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.
29 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
30 Write a Python class to implement pow(x, n)

31 Write a Python class to reverse a string word by word

32 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

33 Write a program to demonstrate Try/except/else

34 Write a program to demonstrate try/finally and with/as


"""1.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.
"""
weight = float(input("enter your weight: "))
pound = (2.2*weight)
print("After converting Kgs into pounds is %0.2f" %pound)

"""
2. Write a program that asks the user to enter three
numbers (use three separate input statements). Create variables
called total and average that hold the sum and average of the
three number and print out the values of total and average.
"""
a=int (input("enter value of a: "))
b=int (input("enter value of b: "))
c=int (input("enter value of c: "))
Total = (a+b+c)
Average = Total/3
print ("sum of three numbers is ", Total)
print ("Average of three numbers is ", Average)
print ("sum of three numbers is %d and Average of three numbers
is %0.2f" %(Total, Average))

"""
3.Write a program that users a for loop to print the numbers
8,11,14,17,20,…,83,86,89.
"""
for i in range(8,90,3):
print( i,end=' ')

"""
4.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 no of
times
"""
username=input("enter your name")"""

5.Use a for loop to print a triangle like the one below.


Allow the user to specify how high the triangle should be.
"""
n=15
for i in range(0,n):
for j in range(0,i+1):
print("*",end=' ')
print( )

n=int(input("how many no of times to print"))


c=1
while c<=n:
print("u r name is",username)
c=c+1

"""
6.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.
"""
import random as ra
random_num = ra.randint(1,10)
guess = int(input('Guess a number between 1 and 10 until you get
it right :'))
while random_num != guess:
print("try again")
guess = int(input('Guess a number between 1 and
10 until you get it right: '))
print('Well guessed! ')

"""
7.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
"""
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if abs(num1 - num2) <= 0.001:
print("close")
else:
print("not close")

"""
8.Write a program that asks the user to enter a word and prints
out whether that word contains any vowels.
"""
vowels = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'I', 'o', 'u']
a=input("enter word")
c=0
for i in a:
if(i in vowels):
c=c+1
if(c!=0):
print("string contains vowels")
else:
print("string dosent contains vowels")

"""
9.Write a program that asks the user to enter two string 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 and appropriate message and exit. If they are of same
length, the program should alternate the characters of the two
strings. For example,
if the user enters abcde and ABCDE the program should print out
AaBbCcDdEe.
"""

a=input("enter string 1: ")


b=input("enter string 2: ")
#result=' '
if(len(a)==len(b)):
for i in range(len(a)):
result=a[i]+b[i]
print(result, end=' ')
else:
print("please enter equal length strings")

"""
10.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.
"""
print('Enter the number')
n=int(input( ))
print("{:,}".format(n))

"""11.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
where appropriate.
"""
n=input()
l=list(n)
print("list is",l)
res=' '
i=0
while(i<len(l)):
if l[i]=='(':
ind=l.index(')')
str=' '.join(l[i:ind+1])
res=res+'*'+str
i=i+len(str)
elif l[i].isalpha():
res=res+'*'+l[i]
i=i+1
else:
res=res+l[i]
i=i+1
print(res)

"""12.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.
"""
import random as ra
list=[]
for i in range (20):list. append(ra. randint(1,100))
print(list)
#print the average of the elements in the list
sum=0
for i in range(20):
sum=sum+list[i]
print("average of all the elements in the list is", sum/
len(list))
#print the second largest and second smallest entries in the
list
lar=lar2=small=small2=list[0]
for i in list[1:]:
if i > lar:
lar2 = lar
lar = i
elif lar2 < i:
lar2 = i
if i < small:
small2 = small
small = i
elif small2 > i:
small2 = i
print("Largest element is : ", lar)
print("Second Largest element is : ", lar2)
print("Smallest element is : ", small)
print("Second Smallest element is : ", small2)
#Print the even numbers in the list
for num in list:
if num%2==0:
print(num,end=' ')
#list comprehension
even = [num for num in list if num % 2 != 0]
print (even)

"""13.Write a program that asks the user for an integer and


Creates a list that consists of the factors of that integer.
"""
x=int(input("enter any number: "))
list1=[]
for i in range (1,x+1):
if x % i == 0:
list1.append(i)
print(list1)
#list comprehension
list=[i for i in range (1,x+1) if x % i == 0]
print(list)

"""14.Write a program that generates 100 random integers that


are either 0 or 1.
Then find the longest run of zeros, the largest number of zeros
in a row.
For instance, the longest run of zeros in
[1,0,1,1,0,0,0,0,1,0,0] is 4.
"""
import random as ra
list=[]
for i in range (100):
list. append(ra.randint(0,1))
print(list)
c=0
maxc=0
for i in list :
if i == 0:
c += 1
else:
if c > maxc:
maxc = c
c = 0
print("the longest run of zeros", maxc)

"""15.Write a program that removes any repeated items from a


list so that
each item appears at most once.
For instance, the list [1,1,2,3,4,3,0,0] would become
[1,2,3,4,0].
"""
list=[1,1,2,3,4,3,0,0]
list1=[]
for i in list:
if i not in list1:
list1.append(i)
print(list1)

"""16.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. Say if the user enters a 1, then the
program converts to inches, if they enter a 2, then the program
converts to yards, etc. while this can be done with if
statements, it is also easier to add new conversions if you use
lists.
"""
n=float(input("Enter Feet"))
list=[]
list.append(n*12)
list.append(n*0.33333)
list.append(n*0.00018939)
list.append(n*304.8)
list.append(n*30.48)
list.append(n/3.2808)
list.append(n/3280.8)
print(list)
print("0.Convert Feet to Inches")
print("1.Convert Feet to Yards")
print("2.Convert Feet to Miles")
print("3.Convert Feet to millimeters")
print("4.Convert Feet to centimeters")
print("5.Convert Feet to meters")
print("6.Convert Feet to kilometers")
op=int(input("Choose Option from Above"))

print(list[op])
"""op=int(input("Choose Options from Above"))

if(op==0):
Inches=n*12
print("Feet to Inches value is",Inches)

if(op==1):
Yards=n*0.33333
print("Feet to Yards value is ",Yards)

if(op==2):
Miles = n*0.00018939
print("Feet to Miles value is ",Miles)

if(op==3):
MM=n* 304.8
print("Feet to millimeters value is ",MM)
if(op==4):
CM=n*30.48
print("Feet to centimeters value is",CM)

if(op==5):
meters=n/3.2808
print("Feet to meters value is",round(meters,3))

if(op==6):
KM=n/3280.8
print("Feet to kilometers value is",KM)
"""

"""17.Write a function called sum_digits that is given an


integer num and returns the sum of the digits of num.
"""
def sum_digits(n):
sum=0
while n>0:
m=n%10
sum=sum+m
n=n//10
return sum
n=int(input("enter value: "))
print("sum of digits is: ", sum_digits(n))

"""18.PROGRAM TO COMPARE TWO STRINGS AND SAY THEY ARE EQUAL OR


NOR"""

print("Enter the First String: ")


strOne = input()
print("Enter the Second String: ")
strTwo = input()

lenOne = len(strOne)
lenTwo = len(strTwo)
if lenOne==lenTwo:
i = 0
chk = 0
while i<lenOne:
if strOne[i] != strTwo[i]:
chk = 1
break
i = i+1
if chk==0:
print("\nStrings are Equal")
else:
print("\nStrings are Not Equal")
else:
print("\nStrings are Not Equal")

"""19.Write a function called number _of_ factor that takes an


integer and returns how many factors the number has.
"""
def number_of_factors(n):
list=[i for i in range (1, n+1)if n % i == 0]
return len(list)
print("number has %d factors" %number_of_factors(200))

"""20.Write a function call is _sorted that is given a list and


returns
Ture if the list is sorted and False otherwise.
"""
def is_sorted1(list2):
c=0
list1=list2[:]
list1.sort()
if(list2 != list1):
c=1
if(not c):
return True
else:
return False
list2= [14,15,82,100,121]
print(is_sorted1(list2))

"""21.Write a function called root that is given a number x and


an integer n and returns x1/n. In the function definition, set
the default value of n to 2.
"""
import math
#Method 1
def root(x,n):
return pow(x,1/n)
n=2
x=int(input("enter value"))
print("Method 1 using pow", root(x,n),
"Method 2, If n value is 2 only using sqrt function",
math.sqrt(x))

"""22.Write a function called primes that is given a number n


and returns a list of the first n primes. Let the default value
of n be 100.
"""
def primes(n):
list=[]
for num in range (n+1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
list.append(num)
return list
n=int(input("enter n value: "))
print("list of n prime numbers are: ", primes(n))

"""23.Write a function called merge that takes two already


sorted lists of
possible different lengths, and merges them into a single sorted
list.
(a) Do this using the sort method. (b) Do this without using the
sort method.
"""
#Without sort method
def merge(list1,list2):
list3=list1+list2
print(list3)
for i in range (len(list3)):
for j in range (i + 1,len(list3)):
if(list3[i] > list3[j]):
temp=list3[i]
list3[i] = list3[j]
list3[j] = temp
print(list3)
list1=[1,2,3,5,6]
list2=[3,5,9,10]
merge(list1,list2)
#sort method
def merge (list1, list2):
list3=list1+list2
list3.sort( )
print("After merging two list in sorted order
",list3)
list1=[1,2,3,5,6]
list2=[3,5,9,10]
merge(list1,list2)

"""24.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 cant
exceed the
number of occurrences of the letter in the users word.
"""
from itertools import permutations
s=input('Enter a word:::')
for i in range (2,len(s)):
for p in permutations(s,i):
print(' '.join(p), end =' ')

"""25. Write a program that reads a file consisting of email


addresses,
each on its own line. Your program should print out a string
consisting
of those email addresses separated by semicolons.
"""
import re

fo=open("sample.txt","r+")

str=fo.read()
print("Read String is: ",str)

lst=re.findall('\S+@\S+',str)

print(";"+lst[0]+";")
fo.close()

"""26.Write a program that reads a list of temperatures from a


file called temps.txt, converts those temperatures Fahrenheit,
and writes the results to a file called ftemps.txt.
"""

fo= open("temps.txt")
f1= open("ftemps.txt","w+")
for i in fo:
c=float(i)
F=(9*c + (32*5))/5
f1.write(str(F)+"\n")
f1.close( )
f0.close( )
"""27. Write a class called product. The class should have
fields called name, amount, and price, holding the products
name, the number of items of that product in stop, and the
regular price of the product. There should be a method get_price
that receives the number of items to be both and returns a the
cost of buying that many items, where the regular price is
changed for orders of less than 10 items, a 10% discount is
applied for orders of between 10 and 99 items, and a 20%
discount is applied for orders of 100 or more items. There
should also be a method called make_purchase that receives the
number of items to be bought and decreases amount by that much.
"""

class Product:
def __init__(self,name,amount,price):
self.name=name
self.amount=amount
self.price=price
def get_price(self, number_items):
if number_items<10:
return self .price*number_items
elif 10 <=number_items < 100:
return 0.9*self.price*number_items
else:return 0.8*self.price*number_items

def make_purchase(self, quantity):


self.amount -= quantity
name, amount, price = 'shoes', 200, 1200

shoes = Product(name, amount, price)

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

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

q3=112
print(f'cost for {q3} {shoes.name} = {shoes.get_price(q3)}')
shoes.make_purchase(q3)
print(f'remaining stock: {shoes.amount}\n')

"""28.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 minute and seconds formatted as in following in the 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
pervious method.
"""
# Python Program to Convert seconds
# into hours, minutes and seconds

def convert_to_minutes(seconds):
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60

return "%d:%02d:%02d" % (hour, minutes, seconds)

# Driver program
n = int(input("Enter seconds"));
print(convert_to_minutes(n))

"""29. Write a class called converter.


The user will pass a length and a unit when declaring an object
from the
classes for example, c=converter (9, ‘inches’).
The possible units are inches, feet, yards, miles, kilometers,
meters,
centimeters, and millimeters. For of those 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.
"""

class Converter:
def __init__(self, n,name):
self.value = n
self.name=name
def FeetToInches(self):
Inches=self.value*12
print("Feet to Inches value is ", Inches)
def milestokm(self):
km=self. value/0.62137
print("miles to KM is ", km)
def FeetToYards(self):
Yards= self.value * 0.3333
print("Feet to Yards value is ", Yards)
def FeetToMiles(self):
Miles= self.value * 0.00018939
print("Feet to Miles value is ", Miles)

n=float(input("enter feet/inches/cm/mm/km/miles: "))


x=Converter(n,'inches')

x.FeetToInches( )
x.milestokm( )
x.FeetToYards( )
x.FeetToMiles( )

"""30. Write a python class to implement pow(x, n).


"""
class power:
def pow1(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.pow1(x, -n)
val = self.pow1(x,n//2)
if n%2 == 0:
return val*val
return val*val*x
x=power( )
print(x.pow1(2, -2))
print(x.pow1(3, 5))
print(x.pow1(100, 0))

"""31. Write a python class to reverse a string word by word.


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

"""32. Write a program that open a file dialog that allows you
to select a text file. The program then displays the contents of
the file in a textbox.
"""
from tkinter import *
from tkinter.filedialog import *
from tkinter.scrolledtext import ScrolledText
#lab program 2 type
root = Tk( )
root.title('File dialog')
textbox = ScrolledText()
textbox.grid( )

filename=askopenfilename(initialdir='c:\python_code\examples',
filetypes=[('Text files', '.txt'), ('All files', '*')])
s = open(filename).read( )
textbox.insert(1.0, s)
mainloop( )

"""33. Write a program to demonstrate Try/except/else


"""
try:
x=int(input('Enter a number upto 100: '))
if x > 100:
raise ValueError(x)
except ValueError:
print(x, "is out of allowed rage")
else:
print(x, "is within the allowed range")

"""34. Write a program to demonstrate try/finally and with/as.


"""
#try/finally

try:
print('try block')
x=int(input("Enter a number:"))
y=int(input("Enter another number:"))
z=x/y
expect ZeroDivisionError:
print("expect ZeroDivisionError block")
print("Division by not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
print ("Out of try, except, else and finally blocks.")

Output1:
try block
Enter a number:100
Enter another number:10
else block
Division = 10.0
finally block
out of try, except, else and finally blocks.
Output2:
try block
Enter a number:100
Enter another number:0
expect ZeroDivisionError block
Division by not accepted
finally block
Out of try, except, else and finally blocks.

with/as
# file handling
#1)without using with statement
file=open('123.txt', 'w')
file.write('hello world')
file.close( )
#2)with try and finally
File=open('123.txt', 'w')
try:
file.write('hello world')
finally:
file.close( )
#3)using with statement
with open('123.txt', 'w') as file:
file.write('hello world')

You might also like