Python Chit
Python Chit
import math
radius = float(input("Enter the radius of the cylinder: "))
height = float(input("Enter the height of the cylinder: "))
surface_area = 2 * math.pi * radius * (radius + height)
volume = math.pi * radius**2 * height
print(f"Surface Area of the Cylinder: {surface_area:.2f} square units")
print(f"Volume of the Cylinder: {volume:.2f} cubic units")
7. Write a program to take input as five subject marks and display the grade.
# Pattern 1
for i in range(1, 6):
print(" " * (5 - i) + "*" * (2*i - 1))
# Pattern 2
for i in range(3, 0, -1):
print(" " * (3 - i) + "*" * (2*i - 1))
9. Write a Python program to find the sum of first 10 natural numbers using for loop.
sum = 0
for i in range(1, 11):
sum += i
# Pattern 3
for i in range(1, 4):
print("*" * i)
11. Write a Python program to print all even numbers between 1 to 100 using while loop.
num = 1
while num <= 100:
if num % 2 == 0:
print(num)
num += 1
def fibonacci(n):
fib_series = [0, 1]
for i in range(2, n):
fib_series.append(fib_series[i-1] + fib_series[i-2])
return fib_series
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
15. Write a Python program takes in a number and finds the sum of digits in a number.
16. Write a Python program that takes a number and checks whether it is a palindrome or
not.
def is_palindrome(n):
return str(n) == str(n)[::-1]
numbers = [1, 2, 3, 4, 5]
product = 1
19. Write a Python program to get the largest number from a list.
20. Write a Python program to get the smallest number from a list.
numbers = [1, 2, 3, 4, 5]
reversed_list = numbers[::-1]
print("Reversed list:", reversed_list)
22. Write a Python program to find common items from two lists.
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
24. Create a tuple and find the minimum and maximum number from it.
my_tuple = (1, 2, 3, 2, 4, 5, 4, 6)
repeated_items = [item for item in my_tuple if my_tuple.count(item) > 1]
repeated_items = list(set(repeated_items)) # Remove duplicates
print("Repeated items in the tuple:", repeated_items)
26. Print the number in words for Example: 1234 => One Two Three Four.
def number_to_words(num):
num_words = {
'0': 'Zero', '1': 'One', '2': 'Two', '3': 'Three', '4': 'Four',
'5': 'Five', '6': 'Six', '7': 'Seven', '8': 'Eight', '9': 'Nine'
}
return ' '.join([num_words[digit] for digit in str(num)])
number = 1234
print(f"{number} => {number_to_words(number)}")
27. Write a Python program to create a set, add member(s) in a set and remove one item
from set.
my_set = {1, 2, 3, 4, 5}
print("Initial set:", my_set)
my_set.add(6)
print("Set after adding 6:", my_set)
my_set.remove(3)
print("Set after removing 3:", my_set)
28. Write a Python program to perform following operations on set: intersection of sets,
union of sets, set difference, symmetric difference, clear a set.
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# Intersection of sets
intersection = set1.intersection(set2)
print("Intersection of sets:", intersection)
# Union of sets
union = set1.union(set2)
print("Union of sets:", union)
# Set difference
difference = set1.difference(set2)
print("Set difference:", difference)
# Symmetric difference
symmetric_difference = set1.symmetric_difference(set2)
print("Symmetric difference:", symmetric_difference)
# Clear a set
set1.clear()
print("Set after clearing:", set1)
29. Write a Python program to find maximum and the minimum value in a set.
31. Write a Python script to sort (ascending and descending) a dictionary by value.
32. Write a Python script to concatenate following dictionaries to create a new one. Sample
Dictionary: dic1 = {1:10, 2:20} dic2 = {3:30, 4:40} dic3 = {5:50, 6:60}
dic1 = {1: 10, 2: 20}
dic2 = {3: 30, 4: 40}
dic3 = {5: 50, 6: 60}
33. Write a Python program to combine two dictionary adding values for common keys.
d1={'a': 100, 'b': 200, 'c':300} d2 ={'a': 300, 'b': 200, 'd':400}
34. Write a Python program to print all unique values in a dictionary. Sample Data:
[{"V":"s001"}, {"V": "$002"}, {"V": "S001"}, {"V": "S005"},{"VII":"S005"}, {"V":"S009"},
{"VIII":"S007"}]
data = [{"V": "s001"}, {"V": "$002"}, {"V": "S001"}, {"V": "S005"}, {"VII":
"S005"}, {"V": "S009"}, {"VIII": "S007"}]
my_dict = {'a': 100, 'b': 200, 'c': 300, 'd': 400, 'e': 500}
highest_values = sorted(my_dict.values(), reverse=True)[:3]
print("Highest 3 values in the dictionary:", highest_values)
36. Write a Python function that accepts a string and calculate the number of upper case
letters and lower case letters.
def count_upper_lower(string):
upper_count = sum(1 for char in string if char.isupper())
lower_count = sum(1 for char in string if char.islower())
return upper_count, lower_count
37. Write a Python program to generate a random float where the value is between 5 and 50
using Python math module
import random
import math
38. Write a Python function that takes a number as a parameter and check the number is
prime or not.
def is_prime(number):
if number <= 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True
39. Write a Python function to calculate the factorial of a number (a non-negative integer).
The function accepts the number as an argument.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
40. Write a Python program to create a user defined module that will ask your college name
and will display the name of the college.
# college_module.py
def get_college_name():
college_name = input("Enter your college name: ")
return college_name
import college_module
college = college_module.get_college_name()
print("College name:", college)
41. Write a Python program that will calculate area and circumference of circle using inbuilt
Math Module
import math
42. Write a Python program that will display Calendar of given month using Calendar
Module.
import calendar
print(calendar.month(year, month))
43. Write a Python program to create two matrices and perform addition, subtraction, and
multiplication and division operation on matrix.
import numpy as np
# Addition
addition = np.add(matrix1, matrix2)
print("Matrix Addition:")
print(addition)
# Subtraction
subtraction = np.subtract(matrix1, matrix2)
print("\nMatrix Subtraction:")
print(subtraction)
# Multiplication
multiplication = np.dot(matrix1, matrix2)
print("\nMatrix Multiplication:")
print(multiplication)
# Division (element-wise)
division = np.divide(matrix1, matrix2)
print("\nMatrix Division:")
print(division)
str1 = "Hello"
str2 = "World"
45. Write a NumPy program to generate six random integers between 10 and 30.
import numpy as np
class MyClass:
def method1(self, n, c):
print(f"Integer: {n}, Character: {c}")
obj = MyClass()
obj.method1(10, 'A')
obj.method2('B', 20)
47. Write a Python program to create a class to print the area of a square and a rectangle.
The class has two methods with the same name but different number of parameters.
The method for printing area of rectangle has two parameters which are length and
breadth respectively while the other method for printing area of square has one
parameter which is side of square.
class AreaCalculator:
def area_rectangle(self, length, breadth):
print(f"Area of Rectangle: {length * breadth}")
obj = AreaCalculator()
obj.area_rectangle(5, 10)
obj.area_square(5)
48. Write a Python program to create a class 'Degree' having a method 'getDegree' that
prints "I got a degree". It has two subclasses namely 'Undergraduate' and 'Postgraduate'
each having a method with the same name that prints "I am an Undergraduate" and "I
am a Postgraduate" respectively. Call the method by creating an object of each of the
three classes.
class Degree:
def getDegree(self):
print("I got a degree")
class Undergraduate(Degree):
def getDegree(self):
print("I am an Undergraduate")
class Postgraduate(Degree):
def getDegree(self):
print("I am a Postgraduate")
degree_obj = Degree()
ug_obj = Undergraduate()
pg_obj = Postgraduate()
degree_obj.getDegree()
ug_obj.getDegree()
pg_obj.getDegree()
49. Create a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information.
class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary
def read_info(self):
self.name = input("Enter employee name: ")
self.department = input("Enter department: ")
self.salary = float(input("Enter salary: "))
def display_info(self):
print(f"Name: {self.name}, Department: {self.department}, Salary:
{self.salary}")
50. Python program to read and print student's information using two classes using simple
inheritance.
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, roll_number):
super().__init__(name)
self.roll_number = roll_number
def display_info(self):
print(f"Name: {self.name}, Roll Number: {self.roll_number}")
class Parent1:
def method1(self):
print("Method 1 from Parent 1")
class Parent2:
def method2(self):
print("Method 2 from Parent 2")
obj = Child()
obj.method1()
obj.method2()
obj.method3()
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero!")
53. Write a Python program to create user defined exception that will check whether the
password is correct or not?
class PasswordError(Exception):
pass
def check_password(password):
correct_password = "Rudra"
if password != correct_password:
raise PasswordError("Incorrect password!")
try:
user_password = input("Enter password: ")
check_password(user_password)
print("Password is correct!")
except PasswordError as e:
print(f"Error: {e}")