Skip to main content

· One min read
Kaustubh Kulkarni

Que > Program to for all type of file Errors occurred in opening a file input by user and perform operation like read write and append on file, close the file in finally block.

file.py
file_name=str(input('Please enter valid file name :'))
try:
f=open(file_name)
n=input("Enter content to write on file :")
f.write(n)
f.close()
except ValueError:
print("ValueError- Please enter valid File Name")
except OSError:
print ("Could not open/read file:", file_name)
except FileNotFoundError:
print ("File does not exists:", file_name)
except IOError:
print('file not found', file_name)
except e as Exception:
print("Exception occured ",e)
finally:
# f.close()
print("Program terminated")
Output

Please enter valid file name :k
Could not open/read file: k
Program terminated

· One min read
Kaustubh Kulkarni

Que > Program for performing some addition, sum, product and division operation on given input and handle all types of Exceptions using Attribute Error, Value Error and Division by Zero Error, etc

file.py
try:
n1=int(input("Enter Integer 1:"))
n2=int(input("Enter Integer 2:"))
print(" N1 * N2 = ", n1*n2)
print(" N1 / N2 =",n1/n2)
print(" N1 + N2 =",n1+n2)
print(" N1 - N2 =",n1-n2)
except ValueError:
print("ValueError- Please enter valid number")
except ZeroDivisionError:
print("ZeroDivisionError: You can not divide number by 0")
except AttributeError:
print("AttributeError: Attribute is not valid")
except e as Exception:
print("Unhandled Exception Ocurred : ",e)
finally:
print("Program terminated")
Output
Enter Integer 1:6
Enter Integer 2:0
N1 * N2 = 0
ZeroDivisionError: You can not divide number by 0
Program terminated

· One min read
Kaustubh Kulkarni

Que > Program to demonstrate the Use of *args and **kwargs

file.py
def adder(*num,**data):
sum = 0
for n in num:
sum = sum + n
print("Sum:",sum)
for key, value in data.items():
print("{} is {}".format(key,value))
adder(3,5,Firstname="K", Lastname="K", Age=222, Phone=1234567890)
Output

Sum: 8
Firstname is K
Lastname is K
Age is 222
Phone is 1234567890

· One min read
Kaustubh Kulkarni

Que > Calculate And Add The Surface Area Of Two Cubes. Use Nested Functions

file.py
def SurfaceAreaOf2Cubes(a1,a2):
A1=6*a1*a1
print("Surface Area of First Cube is ",A1)
def SAO2C(a2):
A2=6*a2*a2
print("Surface Area of Second Cube is ",A2)
def Total(A1,A2):
print("After adding ",A1+A2)
Total(A1,A2)
SAO2C(a2)
SurfaceAreaOf2Cubes(int(input("Enter Edge of First Cube :")),int(input("Enter Edge of First Cube :")))
Output
Enter Edge of First Cube :15
Enter Edge of First Cube :12
Surface Area of First Cube is 1350
Surface Area of Second Cube is 864
After adding 2214