[go: up one dir, main page]

0% found this document useful (0 votes)
8 views10 pages

25-50 Python (Manasi)

The document contains various Python programming tasks, including finding the largest number in a list, creating user-defined exceptions, implementing class inheritance, and performing file operations. It also covers topics such as set operations, bitwise operators, and exception handling. Each task is accompanied by code snippets demonstrating the required functionality.

Uploaded by

gavalimanasi1
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)
8 views10 pages

25-50 Python (Manasi)

The document contains various Python programming tasks, including finding the largest number in a list, creating user-defined exceptions, implementing class inheritance, and performing file operations. It also covers topics such as set operations, bitwise operators, and exception handling. Each task is accompanied by code snippets demonstrating the required functionality.

Uploaded by

gavalimanasi1
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/ 10

#largest no.

numbers=list(map(int,input("enter the numbers: ").split()))


largest=max(numbers)
smallest=min(numbers)
print("largest no: ",largest)
print("smallest no: ",smallest)

#21
num = 2 # Starting number

for i in range(1, 4): # 3 rows total


for j in range(2 * i - 1): # Number of elements: 1, 3, 5
print(num, end=" ")
num += 2
print() # New line after each row

#23 Write a Python program to create user defined exception that will check whether the
password is correct or not.

# User-defined exception
class WrongPassword(Exception):
pass

# Main program
def check_password():
correct_password = "abc123"
password = input("Enter your password: ")

if password != correct_password:
raise WrongPassword("Wrong password! Try again.")
else:
print("Password is correct. Access granted!")
# Run the program
try:
check_password()
except WrongPassword as e:
print(e)

#24)Write a program for overloading and overriding in python.


# Overloading using default arguments
class Add:
def sum(self, a=0, b=0, c=0):
return a + b + c

# Overriding
class Parent:
def show(self):
print("This is Parent class")

class Child(Parent):
def show(self): # Overriding Parent's show method
print("This is Child class")

# Testing
obj1 = Add()
print("Sum:", obj1.sum(5, 10))
obj2 = Child()
obj2.show()

#25)WAP to read contents of first.txt file and write same content in second.txt file.
with open("first.txt", "r") as f1, open("second.txt", "w") as f2:
data = f1.read()
f2.write(data)

#26)Write a program for seek ( ) and tell ( ) function for file pointer manipulation in python .
with open("sample.txt", "w+") as f:
f.write("Hello world!")
f.seek(0) # Move to start
print("Current position:", f.tell()) # Should be 0
content = f.read()
print("Content:", content)
print("Position after reading:", f.tell())

#27)Write a program to create class student with Roll no. and Name and display its contents.
class Student:
def __init__(self, roll, name):
self.roll = roll
self.name = name

def display(self):
print("Roll No:", self.roll)
print("Name:", self.name)
s = Student(101, "Alice")
s.display()

#28)Write a program for four built-in functions on set.


s = {1, 2, 3}
s.add(4)
s.remove(2)
print("Set:", s)
print("Length:", len(s))
s.clear()
print("After clear:", s)

#29)Write a program for bitwise operators in Python .


a = 5 # 0101
b = 3 # 0011

print("AND:", a & b)
print("OR:", a | b)
print("XOR:", a ^ b)
print("NOT a:", ~a)

#30)Write python program to illustrate if else ladder.


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

if x < 0:
print("Negative")
elif x == 0:
print("Zero")
elif x > 0 and x <= 10:
print("Between 1 and 10")
else:
print("Greater than 10")

#31)Write a program for any four operation of List.


lst = [10, 20, 30]
lst.append(40)
lst.remove(20)
lst.insert(1, 25)
lst.sort()
print("List:", lst)

#32)Write Python code for finding greatest among four numbers


a = int(input("Enter 1st: "))
b = int(input("Enter 2nd: "))
c = int(input("Enter 3rd: "))
d = int(input("Enter 4th: "))

greatest = max(a, b, c, d)
print("Greatest:", greatest)

#33)Write python code to count frequency of each characters in a given file


with open("sample.txt", "r") as f:
text = f.read()
freq = {}

for char in text:


if char in freq:
freq[char] += 1
else:
freq[char] = 1

print(freq)

#34)Design a class student with data members; Name, roll number address Create suitable
method for reading and printing students details.
class Student:
def __init__(self):
self.name = ""
self.roll = 0
self.address = ""

def read(self):
self.name = input("Enter Name: ")
self.roll = int(input("Enter Roll No: "))
self.address = input("Enter Address: ")

def display(self):
print("Name:", self.name)
print("Roll No:", self.roll)
print("Address:", self.address)

s = Student()
s.read()
s.display()

#35)Create a parent class named Animals and a child class Herbivorous which will extend the
class Animal. In the child class Herbivorous over side the method feed ( ). Create a object.
class Animal:
def feed(self):
print("Animals need food.")

class Herbivorous(Animal):
def feed(self): # Overriding
print("Herbivorous animals eat plants.")

h = Herbivorous()
h.feed()

#36)Print the following pattern using loop:


for i in range(7, 0, -2):
for j in range(i):
print(j % 2, end=" ")
print()

#37)Write python program to perform following operations on set

s = {1, 2, 3, 4, 5}
print("Set:", s) # Access

s.add(6) # Add
print("After adding:", s)

s.remove(2) # Remove
print("After removing:", s)

#39) Write a python program that takes a number and checks whether it is a palindrome.
n = input("Enter number: ")
if n == n[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")

#41)Write a python program takes in a number and find the sum of digits in a number.
n = input("Enter number: ")
print("Sum:", sum(int(d) for d in n))

#42)Write a program function that accepts a string and calculate the number of uppercase
letters and lower case letters.
def count_case(s):
upper = sum(1 for c in s if c.isupper())
lower = sum(1 for c in s if c.islower())
print("Uppercase:", upper)
print("Lowercase:", lower)

count_case("Hello World")

#43)Write a program function that accepts a string and calculate the number of uppercase
letters and lower case letters
def count_case(s):
upper = sum(1 for c in s if c.isupper())
lower = sum(1 for c in s if c.islower())
print("Uppercase:", upper)
print("Lowercase:", lower)

count_case("Hello World")
#44)Write a python program to generate five random integers between 10 and 50 using
numpy library.
import numpy as np
print(np.random.randint(10, 51, 5))

#45)Write a Python program to create a class ‘Diploma’ having a method ‘getdiploma’ that
prints “I got a diploma”. It has two subclasses namely ‘CO’ and ‘IF’ each having a method
with the same name that prints “I am with CO diploma” and ‘I am with IF diploma’
respectively. Call the method by creating an object of each of the three classes
class Diploma:
def getdiploma(self):
print("I got a diploma")

class CO(Diploma):
def getdiploma(self):
print("I am with CO diploma")

class IF(Diploma):
def getdiploma(self):
print("I am with IF diploma")

d = Diploma()
c = CO()
i = IF()
d.getdiploma()
c.getdiploma()
i.getdiploma()

#46) Write a Python program to create user defined exception that will check whether the
password is correct or not.
#47) Write a Python program to check for zero division errors exception.
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print("Result:", a / b)
except ZeroDivisionError:
print("Cannot divide by zero!")

#48)Design a class student with data members; Name, Roll No., Address. Create suitable
method for reading and printing students detail

#49)Explain Try-except-else-finally block used in exception handling in Python with


example.
try:
x = int(input("Enter number: "))
result = 10 / x
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result:", result)
finally:
print("This block always runs")

#50)Write a Python program to create a class ‘Diploma’ having a method ‘getdiploma’ that
prints “I got a diploma”. It has two subclasses namely ‘CO’ and ‘IF’ each having a method
with the same name that prints “I am with CO diploma” and ‘I am with IF diploma’
respectively. Call the method by creating an object of each of the three classes

You might also like