Python Programs
1. Write simple Python program using operators:a) Arithmetic Operators b) Logical Operators
c) Bitwise Operators
Ans:
# Arithmetic Operators
a = 10
b=5
print("Arithmetic Operators:")
print("a + b =", a + b)
print("a - b =", a - b)
print("a * b =", a * b)
print("a / b =", a / b)
print("a // b =", a // b) # Integer division
print("a % b =", a % b) # Modulus
print("a ** b =", a ** b) # Exponentiation
# Logical Operators
x = True
y = False
print("\nLogical Operators:")
print("x and y =", x and y)
print("x or y =", x or y)
print("not x =", not x)
# Bitwise Operators
p = 10 # 1010 in binary
q = 4 # 0100 in binary
print("\nBitwise Operators:")
print("p & q =", p & q) # Bitwise AND
print("p | q =", p | q) # Bitwise OR
print("p ^ q =", p ^ q) # Bitwise XOR
print("~p =", ~p) # Bitwise NOT
print("p << 1 =", p << 1) # Bitwise left shift
print("p >> 1 =", p >> 1) # Bitwise right shift
2. Write a program that takes the marks of 5 subjects and displays the grade. Write a program
to check whether a number is even or odd.
Ans:
sub1=int(input("Enter the marks of sub1 : "))
sub2=int(input("Enter the marks of sub2 : "))
sub3=int(input("Enter the marks of sub3 : "))
sub4=int(input("Enter the marks of sub4 : "))
sub5=int(input("Enter the marks of sub5 : "))
sum=sub1+sub2+sub3+sub4+sub5
per=sum/500*100
print("Percentage : ",per)
if(per>=75 and per<100):
print("Passed with Distinction")
elif(per>=60 and per<75):
print("Passed with First class")
elif(per>=40 and per<60):
print("Passed with Second class")
else:
print("Failed")
no=int(input("Enter the number : "))
if(no%2==0):
print(no,"is even number")
else:
print(no,"is odd number")
3. Write a program to calculate area and perimeter of the square and Rectangle
Ans:
side = int(input("Enter side of the square: "))
print("Square Area:", side * side)
print("Square Perimeter:", 4 * side)
length = int(input("\nEnter length of the rectangle: "))
breadth = int(input("Enter breadth of the rectangle: "))
print("Rectangle Area:", length * breadth)
print("Rectangle Perimeter:", 2 * (length + breadth))
4. Write a program to check if a Number is Positive, Negative or Zero
Ans:
number = int(input("Enter a number: "))
if number > 0:
print(number, "is Positive.")
elif number < 0:
print(number, "is Negative.")
else:
print("The number is Zero.")
5. Write a Python program to calculate factorial of a number
Ans:
no=int(input("Enter the number : "))
i=1
fact=1
while(i<=no):
fact=fact*i
i=i+1
print("Factorial : ",fact)
6. Write a Python program takes in a number and finds the sum of digits in a number.
Ans:
no=int(input("Enter the number : "))
sum=rem=0
while(no>0):
rem=no%10
sum=sum+rem
no=no//10
print("Sum of digits : ",sum)
7. Write a Python Program to Reverse a Given Number
Ans:
no=int(input("Enter the number : "))
rev=rem=0
while(no>0):
rem=no%10
rev=rev*10+rem
no=no//10
print("Reverse of digits : ",rev)
8. Write a program to check the largest number among the three numbers
Ans:
a = int(input("Enter the number"))
b = int(input("Enter the number"))
c = int(input("Enter the number"))
if a >= b and a >= c:
print(a)
elif b >= a and b >= c:
print(b)
else:
print(c)
9. Write Python program to perform following operations on Lists: Create list, Access list,
Update list (Add item, Remove item), Delete list
Ans:
my_list = [10, 20, 30, 40, 50]
print("Access:", my_list[1])
my_list.append(60)
print("Append:", my_list)
my_list.insert(2, 25)
print("Insert:", my_list)
my_list.extend([70, 80])
print("Extend:", my_list)
print("Slicing [1:4]:", my_list[1:4])
my_list.remove(30)
print("Remove 30:", my_list)
my_list.pop(3)
print("Pop index 3:", my_list)
my_list.clear()
print("Clear:", my_list)
del my_list
print("Deleted")
10. Write Python program to perform following operations on Tuples: Create Tuple, Access
Tuple, Update Tuple, Delete Tuple
Ans:
t1 = (10, 20, 30)
t2 = (40, 50)
print("Access:", t1[1])
t3 = t1 + t2
print("New Tuple:", t3)
del t3
print("Tuple Deleted")
11. Write Python program to perform following operations on Set: Create Set, Access Set
elements, Update Set,Delete set
Ans:
s = {10, 20, 30}
for i in s:
print("Access:", i)
s.add(40)
s.update([50, 60])
print("Updated:", s)
s.remove(20)
print("After Remove:", s)
del s
print("Set Deleted")
12. Write Python program to perform following operations on Dictionaries: Create Dictionary,
Access Dictionary elements, Update Dictionary, Delete Dictionary, Looping through
Dictionary
Ans:
d = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print("Access:", d['name'])
d['age'] = 26
d['country'] = 'USA'
print("Updated:", d)
del d['city']
print("After Delete:", d)
for k, v in d.items():
print(k, ":", v)
del d
print("Dictionary Deleted")
13. Write Python program to demonstrate math built-in functions
Ans:
import math
x = 4.3
y=5
z=2
print("Ceil:", math.ceil(x))
print("Cos:", math.cos(math.radians(60)))
print("Exp:", math.exp(1))
print("Factorial:", math.factorial(y))
print("Pow:", math.pow(y, z))
print("Sqrt:", math.sqrt(25))
print("Sin:", math.sin(math.radians(30)))
print("Tan:", math.tan(math.radians(45)))
14. Write Python program to demonstrate string built-in functions
Ans:
s = "hello world 123"
s2 = "Python123"
print("Capitalize:", s.capitalize())
print("Count 'l':", s.count('l'))
print("Find 'world':", s.find('world'))
print("Index of 'o':", s.index('o'))
print("Is Alnum:", s2.isalnum())
print("Is Alpha:", s.isalpha())
print("Is Digit:", "123".isdigit())
print("Is Lower:", s.islower())
print("Is Numeric:", "12345".isnumeric())
print("Lower:", "HELLO".lower())
print("Replace:", s.replace("world", "Python"))
print("Split:", s.split())
15. Write a Python function that takes a number as a parameter and check the number is
prime or not.
Ans:
def prime(no):
count=0
for j in range(2,no):
if(num%j==0):
count=count+1
break
if(count==0):
print("It is prime number")
else:
print("It is not prime number")
num=int(input("Enter the number : "))
prime(num)
16. Write a Python function that accepts a string and calculate the number of upper case
letters and lower case letters.
Ans:
def count_case(s):
upper = 0
lower = 0
for ch in s:
if ch.isupper():
upper += 1
elif ch.islower():
lower += 1
print("Uppercase letters:", upper)
print("Lowercase letters:", lower)
text = input("Enter a string: ")
count_case(text)
17. Write a Python program to create a user defined module that will ask your college name
and will display the name of the college
Ans:
# college.py (User-defined module)
def display_college_name():
college_name = input("Enter your college name: ")
print("Your college name is:", college_name)
# main.py (Program that uses the module)
import college
college.display_college_name()
18. Write Python program to demonstrate use of user defined packages
Ans:
Step 1: Create the myfolder Package
myfolder/__init__.py # Leave this file empty
myfolder/student.py:
# myfolder/student.py
def show_student_info():
name = input("Enter student name: ")
marks = int(input("Enter marks: "))
print("Student Name:", name)
print("Marks:", marks)
Step 2: Create the Main Program
main.py #outside the myfolder
# main.py
from myfolder import student
student.show_student_info()
19. Write a program in Python to demonstrate Method overriding
Ans:
class Employee:
def get(self):
self.name = input("Enter employee name: ")
self.salary = int(input("Enter employee salary: "))
def display(self):
print("Employee Name:", self.name)
print("Salary:", self.salary)
class Manager(Employee):
def get(self):
self.name = input("Enter manager name: ")
self.salary = int(input("Enter manager salary: "))
self.department = input("Enter department: ")
def display(self):
print("Manager Name:", self.name)
print("Salary:", self.salary)
print("Department:", self.department)
# Employee object
e = Employee()
e.get()
e.display()
# Manager object
m = Manager()
m.get()
m.display()
20. Create a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information
Ans:
class Employee:
def get_info(self):
self.name = input("Enter employee name: ")
self.department = input("Enter department: ")
self.salary = int(input("Enter salary: "))
def display_info(self):
print("Employee Name:", self.name)
print("Department:", self.department)
print("Salary:", self.salary)
# Create and use the object
emp = Employee()
emp.get_info()
emp.display_info()
21. Write a Python program to implement multiple inheritance
Ans:
class Person:
def get_name(self):
self.name = input("Enter name: ")
class Job:
def get_job(self):
self.job = input("Enter job title: ")
class Employee(Person, Job):
def display(self):
print("Name:", self.name)
print("Job Title:", self.job)
# Create object
e = Employee()
e.get_name()
e.get_job()
e.display()
22. Write a Python program to Check for ZeroDivisionError Exception.
Ans:
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
23. Write a Python program to create user defined exception that will check whether
the password is correct or not?
Ans:
class myException(Exception):
pass
try:
un=input("Enter the username : ")
pas=input("Enter the password : ")
if(un=="ITE" and pas=="ite123"):
print("Login Successfully")
else:
raise myException("Invalid username and password")
except myException as e:
print(e)