Python Slip 1

2962dc9c33b44cb9bbd2d9be55f5b453

Q1. Write a python program to show use of multiple exception handing.

try:
    # defining variables
    a = 10
    b= 0
    c = "abc"
    d =a+c
# Zerodivision error
except ZeroDivisionError:
    print("Zero Division Error occurs")
# index error
except IndexError:
    print("Index error occurs")
# type error
except TypeError:
    print("Type error occurs")
Type error occurs

Q2. Write a python function to check whether a number is perfect or not.

Hint: A number is said to be the perfect number if the sum of its proper divisors (not including the number itself) is equal to the number. To get a better idea let’s consider an example, proper divisors of 6 are 1, 2, 3. Now the sum of these divisors is equal to 6 (1+2+3=6), so 6 is said to be a perfect number. Whereas if we consider another number like 12, proper divisors of 12 are 1, 2, 3, 4, 6. Now the sum of these divisors is not equal to 12, so 12 is not a perfect number.

n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
    if(n % i == 0):
        sum1 = sum1 + i
if (sum1 == n):
    print(n," is a Perfect number!")
else:
    print(n," is not a Perfect number!")
Enter any number: 6
6  is a Perfect number!

Q2. Write a python program to display only those words from the text file which contains three characters in it.

import os
def read_data():
    f = open(r"C:/Users/RAHUL/Desktop/MSC_CA/test.txt", 'r')
    s = f.read()
    x = s.split()
    for i in x:
        if len(i) ==3:
            print(i)

read_data()
Rah
Son
may
jun
tal
nsk

0 Comments:

Post a Comment