Assignment 1
1. A cashier has currency notes of denomination 1, 5 and 10. Write python script to accept the amount to be withdrawn from the user and print the total number of currency notes of each denomination the cashier will have to give.
=>
amount = int(input("Enter the amount to withdraw: "))
# Calculating number of 10, 5, and 1 denomination notes
tens = amount // 10
amount %= 10
fives = amount // 5
amount %= 5
ones = amount
print(f"10 Rs notes: {tens}, 5 Rs notes: {fives}, 1 Rs notes: {ones}")
Sample Input and Output**:
Enter the amount to withdraw: 87
10 Rs notes: 8, 5 Rs notes: 1, 1 Rs notes: 2
2. Write a python script to accepts annual basic salary of an employee and calculates and displays the Income tax as per the following rules.
Basic: < 2,50,000 Tax = 0
Basic: 2,50,000 to 5,00,000 Tax = 10%
Basic: > 5,00,000 Tax = 20
=>
salary = float(input("Enter your annual basic salary: "))
if salary < 250000:
tax = 0
elif 250000 <= salary <= 500000:
tax = salary * 0.10
else:
tax = salary * 0.20
print(f"Income tax: Rs. {tax}")
Sample Input and Output
Enter your annual basic salary: 450000
Income tax: Rs. 45000.0
=>
x = float(input("Enter x-coordinate: "))
y = float(input("Enter y-coordinate: "))
if x > 0 and y > 0:
print("The point is in the 1st quadrant.")
elif x < 0 and y > 0:
print("The point is in the 2nd quadrant.")
elif x < 0 and y < 0:
print("The point is in the 3rd quadrant.")
elif x > 0 and y < 0:
print("The point is in the 4th quadrant.")
elif x == 0 and y == 0:
print("The point is at the origin.")
else:
print("The point lies on an axis.")
Enter x-coordinate: -3
Enter y-coordinate: 4
The point is in the 2nd quadrant.
=>
cost_price = float(input("Enter the cost price: "))
selling_price = float(input("Enter the selling price: "))
if selling_price > cost_price:
profit = selling_price - cost_price
print(f"Profit of Rs. {profit}")
elif cost_price > selling_price:
loss = cost_price - selling_price
print(f"Loss of Rs. {loss}")
else:
print("No profit, no loss.")
Sample Input and Output
Enter the cost price: 500
Enter the selling price: 600
Profit of Rs. 100
Set A
=>
num = int(input("Enter a number: "))
sum_of_digits = sum(int(digit) for digit in str(num))
print(f"Sum of digits: {sum_of_digits}")
Sample Input and Output**:
Enter a number: 1234
Sum of digits: 10
2. Write python script to check whether a input number is Armstrong number or not.
num = int(input("Enter a number: "))
order = len(str(num))
sum_of_powers = sum(int(digit) ** order for digit in str(num))
if num == sum_of_powers:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
Sample Input and Output:
Enter a number: 153
153 is an Armstrong number.
num = int(input("Enter a number: "))
sum_of_divisors = sum(i for i in range(1, num) if num % i == 0)
if num == sum_of_divisors:
print(f"{num} is a perfect number.")
else:
print(f"{num} is not a perfect number.")
Enter a number: 6
6 is a perfect number.
x = int(input("Enter the base (X): "))
y = int(input("Enter the exponent (Y): "))
result = x ** y
print(f"{x} raised to the power {y} is {result}")
**Sample Input and Output**:
Enter the base (X): 2
Enter the exponent (Y): 3
2 raised to the power 3 is 8
num = input("Enter a number: ")
if num == num[::-1]:
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")
**Sample Input and Output**:
Enter a number: 121
121 is a palindrome.
6. Write a program to calculate sum of first and last digit of a number.
num = input("Enter a number: ")
first_digit = int(num[0])
last_digit = int(num[-1])
sum_of_digits = first_digit + last_digit
print(f"Sum of first and last digit: {sum_of_digits}")
Sample Input and Output**:
Enter a number: 1234
Sum of first and last digit: 5
Set B
num = input("Enter a number: ")
evens = sum(1 for digit in num if int(digit) % 2 == 0 and digit != '0')
odds = sum(1 for digit in num if int(digit) % 2 != 0)
zeros = num.count('0')
print(f"Evens: {evens}, Odds: {odds}, Zeros: {zeros}")
Enter a number: 102304
Evens: 3, Odds: 2, Zeros: 2
2. Write a program to accept a binary number and convert it into decimal number
binary = input("Enter a binary number: ")
decimal = int(binary, 2)
print(f"Decimal equivalent: {decimal}")
Sample Input and Output:
Enter a binary number: 1010
Decimal equivalent: 10
n = int(input("Enter a number: "))
if 1 <= n <= 50:
print("Ok")
else:
print("Out of range")
Sample Input and Output**:
Enter a number: 30
Ok
n = int(input("Enter a number: "))
for num in range(2, n + 1):
prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
prime = False
break
if prime:
print(num, end=" ")
Sample Input and Output**:
Enter a number: 10
2 3 5 7
start = int(input("Enter the start of range: "))
end = int(input("Enter the end of range: "))
for i in range(start, end + 1):
print(f"\nMultiplication table of {i}:")
for j in range(1, 11):
print(f"{i} x {j} = {i * j}")
Sample Input and Output
Enter the start of range: 2
Enter the end of range: 3
Multiplication table of 2:
2 x 1 = 2
2 x 2 = 4
...
3 x 10 = 30
Set C
n = int(input("Enter the number of lines: "))
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end=" ")
for k in range(i - 1, 0, -1):
print(k, end=" ")
print()
Sample Input and Output**:
Enter the number of lines: 4
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
Assignment 2
Practice Set
1.
Write a python script to create a list and display the list element in reverse
order
my_list
= [1, 2, 3, 4, 5]
print("Original
List:", my_list)
print("Reversed
List:", my_list[::-1])
Output:
Original
List: [1, 2, 3, 4, 5]
Reversed
List: [5, 4, 3, 2, 1]
2.
Python script to display alternate characters of a string from both directions:
my_string
= "Python"
forward
= my_string[::2]
backward
= my_string[::-2]
print("Forward
Alternate Characters:", forward)
print("Backward
Alternate Characters:", backward)
Output:
Forward
Alternate Characters: Pto
Backward
Alternate Characters: nhy
3.
Python program to count vowels and consonants in a string:
#
Count vowels and consonants in a string
def count_vowels_consonants(string):
vowels = "aeiouAEIOU"
v_count = c_count = 0
for char in string:
if char.isalpha():
if char in vowels:
v_count += 1
else:
c_count += 1
return v_count, c_count
string
= "Hello World"
vowels,
consonants = count_vowels_consonants(string)
print("Vowels:",
vowels)
print("Consonants:",
consonants)
Output:
Vowels:
3
Consonants:
7
Set A
1.
Python script to check for duplicates among 5 integers:
#
Check for duplicates in 5 integers
numbers
= [32, 45, 90, 45, 6]
if len(numbers)
!= len(set(numbers)):
print("DUPLICATES")
else:
print("ALL UNIQUE")
Output:
DUPLICATES
2.
Python script to count the character frequency in a string:
#
Count character frequency in a string
string
= 'google.com'
frequency
= {}
for char
in string:
frequency[char] = frequency.get(char, 0) + 1
print(frequency)
Output:
{'g':
2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}
3.
Python program to remove characters with odd index values:
#
Remove characters with odd index values
string
= "abcdef"
result
= string[::2]
print("Result:",
result)
Output:
Result:
ace
4.
Python program to implement a stack using a list:
#
Implement stack using list
stack
= []
stack.append(10)
stack.append(20)
stack.append(30)
print("Stack
after pushing elements:", stack)
stack.pop()
print("Stack
after popping an element:", stack)
Output:
Stack
after pushing elements: [10, 20, 30]
Stack
after popping an element: [10, 20]
5.
Python program to replace occurrences of the first char with '$' except the
first char itself:
#
Replace occurrences of the first character with '$'
string
= "restart"
first_char
= string[0]
result
= first_char + string[1:].replace(first_char, '$')
print("Result:",
result)
Output:
Result:
resta$t
Set B
1.
Python program to create a string with the first 2 and last 2 chars:
#
Create a string with first 2 and last 2 chars
def first_last_chars(string):
if len(string) < 2:
return "Empty String"
return string[:2] + string[-2:]
print(first_last_chars("General12"))
print(first_last_chars("Ka"))
print(first_last_chars("K"))
Output:
Ge12
KaKa
Empty
String
2.
Python program to swap the first two characters of two strings:
#
Swap first two characters of two strings
def swap_first_two_chars(str1,
str2):
return str2[:2] + str1[2:], str1[:2] + str2[2:]
str1,
str2 = "abc", "xyz"
result
= swap_first_two_chars(str1, str2)
print("Result:",
result)
Output:
Result:
('xyc', 'abz')
3.
Python program to count word occurrences in a sentence:
#
Count word occurrences in a sentence
sentence
= "the quick brown fox jumps over the lazy dog"
words
= sentence.split()
word_count
= {}
for
word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
Output:
{'the':
2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}
4.
Python program to implement a queue using a list:
#
Implement queue using list
queue
= []
queue.append(1)
queue.append(2)
queue.append(3)
print("Queue
after enqueue:", queue)
queue.pop(0)
print("Queue
after dequeue:", queue)
Output:
Queue
after enqueue: [1, 2, 3]
Queue
after dequeue: [2, 3]
5.
Python program to count repeated characters in a string:
#
Count repeated characters in a string
string
= "thequickbrownfoxjumpsoverthelazydog"
char_count
= {}
for char
in string:
if string.count(char) > 1:
char_count[char] = string.count(char)
print(char_count)
Output:
{'t':
2, 'h': 2, 'e': 3, 'u': 2, 'r': 2, 'o': 4}
---
Set C
1.
Python program to implement binary search in a sorted list:
#
Binary search function
def binary_search(lst,
item):
low = 0
high = len(lst) - 1
while low <= high:
mid = (low + high) // 2
if lst[mid] == item:
return mid
elif lst[mid] < item:
low = mid + 1
else:
high = mid - 1
return -1
sorted_list
= [1, 3, 5, 7, 9, 11]
item_to_search
= 7
result
= binary_search(sorted_list, item_to_search)
print("Item
found at index:", result)
Output:
Item
found at index: 3
Assignment 3
Set A
1.
Python program to find maximum and minimum values in a set:
#
Find maximum and minimum values in a set
my_set
= {10, 25, 3, 56, 89, 23}
print("Maximum
value:", max(my_set))
print("Minimum
value:", min(my_set))
Output:
Maximum
value: 89
Minimum
value: 3
2.
Python program to add an item to a tuple:
#
Add an item to a tuple
my_tuple
= (1, 2, 3)
new_item
= 4
my_tuple
= my_tuple + (new_item,)
print("Updated
tuple:", my_tuple)
Output:
Updated
tuple: (1, 2, 3, 4)
3.
Python program to convert a tuple to a string:
#
Convert a tuple to a string
my_tuple
= ('H', 'e', 'l', 'l', 'o')
string
= ''.join(my_tuple)
print("String:",
string)
Output:
String:
Hello
4.
Python program to create an intersection of sets:
#
Intersection of sets
set1
= {1, 2, 3, 4}
set2
= {3, 4, 5, 6}
intersection
= set1 & set2
print("Intersection:",
intersection)
Output:
Intersection:
{3, 4}
5.
Python program to create a union of sets:
#
Union of sets
set1
= {1, 2, 3}
set2
= {3, 4, 5}
union
= set1 | set2
print("Union:",
union)
Output:
Union:
{1, 2, 3, 4, 5}
6.
Python script to check if a given key exists in a dictionary:
#
Check if a key exists in a dictionary
my_dict
= {'a': 1, 'b': 2, 'c': 3}
key =
'b'
if
key in my_dict:
print(f"Key '{key}' exists.")
else:
print(f"Key '{key}' does not exist.")
Output:
Key 'b'
exists.
7.
Python script to sort a dictionary by value (ascending and descending):
#
Sort dictionary by value
my_dict
= {'a': 3, 'b': 1, 'c': 2}
asc_sorted
= dict(sorted(my_dict.items(), key=lambda item: item[1]))
desc_sorted
= dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
print("Ascending:",
asc_sorted)
print("Descending:",
desc_sorted)
Output:
Ascending:
{'b': 1, 'c': 2, 'a': 3}
Descending:
{'a': 3, 'c': 2, 'b': 1}
---
Set B
1.
Python program to create set difference and symmetric difference:
#
Set difference and symmetric difference
set1
= {1, 2, 3, 4}
set2
= {3, 4, 5, 6}
difference
= set1 - set2
sym_diff
= set1 ^ set2
print("Difference:",
difference)
print("Symmetric
Difference:", sym_diff)
Output:
Difference:
{1, 2}
Symmetric
Difference: {1, 2, 5, 6}
2.
Python program to create a list of tuples with number and its square:
#
List of tuples with number and its square
numbers
= [1, 2, 3, 4]
result
= [(x, x2) for x in numbers]
print("List
of tuples:", result)
Output:
List
of tuples: [(1, 1), (2, 4), (3, 9), (4, 16)]
3.
Python program to unpack a tuple into several variables:
#
Unpack a tuple into variables
my_tuple
= (10, 20, 30)
a,
b, c = my_tuple
print("a:",
a)
print("b:",
b)
print("c:",
c)
Output:
a: 10
b: 20
c: 30
4.
Python program to get the 4th element from front and last of a tuple:
#
Get 4th element from front and last
my_tuple
= (1, 2, 3, 4, 5, 6, 7)
print("4th
from front:", my_tuple[3])
print("4th
from last:", my_tuple[-4])
Output:
4th
from front: 4
4th
from last: 4
5.
Python program to find repeated items in a tuple:
#
Find repeated items in a tuple
my_tuple
= (1, 2, 3, 2, 4, 5, 1)
repeated
= set([x for x in my_tuple if my_tuple.count(x) > 1])
print("Repeated
items:", repeated)
Output:
Repeated
items: {1, 2}
6.
Python program to check if an element exists in a tuple:
#
Check if element exists in a tuple
my_tuple
= (1, 2, 3, 4, 5)
element
= 3
if
element in my_tuple:
print(f"{element} exists in the tuple.")
else:
print(f"{element} does not exist in the tuple.")
Output:
3
exists in the tuple.
7.
Python script to concatenate dictionaries:
#
Concatenate dictionaries
dic1
= {1: 10, 2: 20}
dic2
= {3: 30, 4: 40}
dic3
= {5: 50, 6: 60}
concatenated_dict
= {dic1, dic2, dic3}
print("Concatenated
Dictionary:", concatenated_dict)
Output:
Concatenated
Dictionary: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
---
Set C
1.
Python program to create a shallow copy of sets:
#
Create a shallow copy of a set
set1
= {1, 2, 3}
shallow_copy
= set1.copy()
print("Original
Set:", set1)
print("Shallow
Copy:", shallow_copy)
Output:
Original
Set: {1, 2, 3}
Shallow
Copy: {1, 2, 3}
2.
Python program to combine two dictionaries by adding values for common keys:
from
collections import Counter
#
Combine two dictionaries adding values for common keys
d1 =
{'a': 100, 'b': 200, 'c': 300}
d2 =
{'a': 300, 'b': 200, 'd': 400}
combined_dict
= Counter(d1) + Counter(d2)
print("Combined
Dictionary:", combined_dict)
Output:
Combined
Dictionary: Counter({'a': 400, 'b': 400, 'c': 300, 'd': 400})
Assignment 4
---
Practice Set
1.
Python program to print the calendar of a specific month and year:
import
calendar
#
Print calendar of a specific month and year
year
= 2024
month
= 10
print(calendar.month(year,
month))
Output:
October 2024
Mo
Tu We Th Fr Sa Su
1
2 3 4 5 6
7
8 9 10 11 12 13
14 15
16 17 18 19 20
21 22
23 24 25 26 27
28 29
30 31
2.
Python script to display datetime in various formats:
from
datetime import datetime
#
Current date and time
now =
datetime.now()
#
Display various datetime formats
print("Current
date and time:", now)
print("Current
year:", now.year)
print("Month
of year:", now.strftime("%B"))
print("Week
number of the year:", now.strftime("%U"))
print("Weekday
of the week:", now.strftime("%A"))
print("Day
of year:", now.strftime("%j"))
print("Day
of the month:", now.day)
print("Day
of week:", now.weekday())
Output:
Current
date and time: 2024-10-08 12:34:56
Current
year: 2024
Month
of year: October
Week
number of the year: 40
Weekday
of the week: Tuesday
Day
of year: 282
Day
of the month: 8
Day
of week: 1
3.
Anonymous function to find the area of a circle:
#
Lambda function to calculate area of a circle
area_circle
= lambda r: 3.14 * r * r
radius
= 5
print("Area
of circle:", area_circle(radius))
Output:
Area
of circle: 78.5
---
Set A
1.
Recursive function to print a string in reverse order:
def reverse_string(s):
if len(s) == 0:
return ""
else:
return s[-1] + reverse_string(s[:-1])
string
= "Hello"
print("Reversed
string:", reverse_string(string))
Output:
Reversed
string: olleH
2.
Python script using a function to calculate \(X^Y\):
def power(x,
y):
return x y
print("Result
of 2^3:", power(2, 3))
Output:
Result
of 2^3: 8
3.
Function to find the union and intersection of two strings:
def union_intersection(str1,
str2):
set1, set2 = set(str1), set(str2)
union = set1 | set2
intersection = set1 & set2
return union, intersection
str1
= "apple"
str2
= "orange"
union,
intersection = union_intersection(str1, str2)
print("Union:",
union)
print("Intersection:",
intersection)
Output:
Union:
{'p', 'a', 'n', 'r', 'g', 'o', 'l', 'e'}
Intersection:
{'a', 'e'}
4.
Recursive function to calculate the sum of digits of a number:
def sum_of_digits(n):
if n == 0:
return 0
else:
return n % 10 + sum_of_digits(n // 10)
num =
12345
print("Sum
of digits:", sum_of_digits(num))
Output:
Sum
of digits: 15
5.
Generator function to generate even numbers up to n:
def even_numbers(n):
for i in range(0, n+1, 2):
yield i
n = 10
for
num in even_numbers(n):
print(num, end=" ")
Output:
0 2 4
6 8 10
---
Set B
1.
Python script to generate Fibonacci terms using generator function:
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
n = 10
for term
in fibonacci(n):
print(term, end=" ")
Output:
0 1 1
2 3 5 8 13 21 34
2.
Python script to calculate the area and volume of a cylinder and cuboid:
import
math
#
Area and volume of cylinder
def cylinder_area_volume(radius,
height):
area = 2 * math.pi * radius * (radius + height)
volume = math.pi * radius2 * height
return area, volume
#
Area and volume of cuboid
def cuboid_area_volume(length,
width, height):
area = 2 * (length * width + width * height + length * height)
volume = length * width * height
return area, volume
print("Cylinder
(area, volume):", cylinder_area_volume(3, 5))
print("Cuboid
(area, volume):", cuboid_area_volume(2, 3, 4))
Output:
Cylinder
(area, volume): (150.79644737231007, 141.3716694115407)
Cuboid
(area, volume): (52, 24)
3.
Python script to convert a decimal number to binary and octal:
def convert_to_binary_octal(num):
binary = bin(num)
octal = oct(num)
return binary, octal
decimal
= 10
binary,
octal = convert_to_binary_octal(decimal)
print("Binary:",
binary)
print("Octal:",
octal)
Output:
Binary:
0b1010
Octal:
0o12
4.
Function to print a dictionary where keys are numbers 1 to 20 and values are
squares:
def generate_square_dict():
return {x: x2 for x in range(1, 21)}
square_dict
= generate_square_dict()
print(square_dict)
Output:
{1: 1,
2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144,
13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361, 20: 400}
5.
Generator function to generate prime numbers up to n:
def prime_numbers(n):
for num in range(2, n+1):
for i in range(2, num):
if num % i == 0:
break
else:
yield num
n = 20
for
prime in prime_numbers(n):
print(prime, end=" ")
Output:
2 3 5
7 11 13 17 19
---
Set C
1.
Program to illustrate function duck typing:
class
Bird:
def fly(self):
print("Bird is flying.")
class
Airplane:
def fly(self):
print("Airplane is flying.")
def test_flying(object):
object.fly()
bird
= Bird()
airplane
= Airplane()
test_flying(bird)
# Bird is flying
test_flying(airplane)
# Airplane is flying
Output:
Bird
is flying.
Airplane
is flying.
This
demonstrates duck typing, where any object with a `fly()` method can be passed
to `test_flying()`.
Assignment 5
Set A
1)
Python Program to Accept, Delete, and Display Student Details using Classes
This
program uses a class to manage student details, including roll number, name,
marks, and calculating the percentage.
class
Student:
def __init__(self, roll_no, name, marks):
self.roll_no = roll_no
self.name = name
self.marks = marks
def display(self):
total_marks = sum(self.marks)
percentage = (total_marks / 300) * 100
print(f"Roll No: {self.roll_no}, Name: {self.name},
Marks: {self.marks}, Percentage: {percentage:.2f}%")
def delete(self):
self.roll_no = None
self.name = None
self.marks = None
#
Accepting student details
students
= []
students.append(Student(101,
"John", [78, 85, 90]))
students.append(Student(102,
"Jane", [88, 76, 95]))
#
Display student details
for
student in students:
student.display()
#
Deleting first student's details
students[0].delete()
print("\nAfter
deleting student 101 details:")
students[0].display()
2)
Python Program to Define a Circle with Center and Radius
This
program accepts a point as the center and radius to define a circle.
class
Point:
def __init__(self, x, y):
self.x = x
self.y = y
class
Circle:
def __init__(self, radius, center):
self.radius = radius
self.center = center
def display(self):
print(f"Circle with center at ({self.center.x},
{self.center.y}) and radius {self.radius}")
#
Accept user input
x, y
= map(int, input("Enter center point (x y): ").split())
radius
= int(input("Enter radius: "))
center
= Point(x, y)
#
Create a circle object
circle
= Circle(radius, center)
circle.display()
3)
Python Class with `get_String` and `print_String` Methods
This
class accepts a string, prints it in uppercase, then reverses and prints it
word by word in lowercase.
class
StringManipulator:
def get_string(self):
self.string = input("Enter a string: ")
def print_string(self):
print("Uppercase:", self.string.upper())
reversed_string = ' '.join(self.string.split()[::-1])
print("Reversed and Lowercase:",
reversed_string.lower())
#
Create object and use methods
sm =
StringManipulator()
sm.get_string()
sm.print_string()
4)
Python Class for Complex Number Addition with Operator Overloading
This
class performs addition of two complex numbers using operator overloading.
class
Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
return Complex(self.real + other.real, self.imag +
other.imag)
def display(self):
print(f"{self.real} + {self.imag}i")
#
Create complex number objects
c1 =
Complex(3, 4)
c2 =
Complex(5, 6)
#
Add complex numbers
result
= c1 + c2
result.display()
---
Set B
1)
Rectangle Class to Compute Area and Volume
This
class calculates the area of a rectangle.
class
Rectangle:
def __init__(self, length, width, height):
self.length = length
self.width = width
self.height = height
def compute_area(self):
return self.length * self.width
def compute_volume(self):
return self.length * self.width * self.height
#
Create rectangle object and compute area and volume
rect
= Rectangle(5, 3, 4)
print("Area:",
rect.compute_area())
print("Volume:",
rect.compute_volume())
2)
Function to Check if a Point Lies on the Boundary of a Circle
class
Point:
def __init__(self, x, y):
self.x = x
self.y = y
class
Circle:
def __init__(self, center, radius):
self.center = center
self.radius = radius
def
pt_in_circle(circle, point):
distance = ((point.x - circle.center.x) 2 + (point.y -
circle.center.y) 2) 0.5
return distance == circle.radius
#
Define a circle and a point
circle
= Circle(Point(0, 0), 5)
point
= Point(3, 4)
#
Check if the point lies on the boundary
print("Point
on boundary:", pt_in_circle(circle, point))
3)
Class to Get All Possible Subsets of a Set
from
itertools import combinations
class
SetManipulator:
def __init__(self, input_set):
self.input_set = input_set
def get_subsets(self):
subsets = []
for r in range(len(self.input_set) + 1):
subsets.extend(combinations(self.input_set,
r))
return subsets
#
Accept set from user
input_set
= {1, 2, 3}
set_manip
= SetManipulator(input_set)
subsets
= set_manip.get_subsets()
print("Subsets:",
subsets)
4)
Class to Display n Repetitions of a String with Operator Overloading
class
Repeater:
def __init__(self, string):
self.string = string
def __mul__(self, n):
return self.string * n
#
Accept string and repetition count from user
string
= input("Enter a string: ")
n =
int(input("Enter repetition count: "))
repeater
= Repeater(string)
print(repeater
* n)
---
Set
C
1)
Python Program for a Basic Calculator Class
class
Calculator:
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
return x / y if y != 0 else "Division by zero
error"
#
Create calculator object and perform operations
calc
= Calculator()
print("Addition:",
calc.add(5, 3))
print("Subtraction:",
calc.subtract(5, 3))
print("Multiplication:",
calc.multiply(5, 3))
print("Division:",
calc.divide(5, 3))
2)
Program to Get Current Date and Day of the Week Using `datetime` Module
import
datetime
#
Get current date and time
current_datetime
= datetime.datetime.now()
#
Print current day of the week
print("Current
date and time:", current_datetime)
print("Day
of the week:", current_datetime.strftime("%A"))
Assignment 6
Practice Set
1)
Python Program to Demonstrate Single Inheritance using `findArea()` Function
class
Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def findArea(self):
return self.length * self.width
class
Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
#
Demonstrate single inheritance
sq =
Square(5)
print(f"Area
of square: {sq.findArea()}")
2)
Python Program Showing the Simplest Form of Inheritance using `info()` Function
class
Parent:
def info(self):
print("This is the parent class")
class
Child(Parent):
def info(self):
print("This is the child class")
#
Demonstrate simple inheritance
c =
Child()
c.info()
---
Set
A
1)
Python Program Demonstrating Multilevel Inheritance
class
Team:
def team_info(self):
print("This is the base class 'Team'")
class
Dev(Team):
def dev_info(self):
print("This is the derived class 'Dev'")
class
Developer(Dev):
def developer_info(self):
print("This is the multilevel derived class 'Developer'")
#
Demonstrate multilevel inheritance
dev
= Developer()
dev.team_info()
dev.dev_info()
dev.developer_info()
2)
Python Program Demonstrating Multiple Inheritance
class
TeamMember:
def team_member_info(self):
print("This is the base class 'TeamMember'")
class
TeamLeader:
def team_leader_info(self):
print("This is the base class 'TeamLeader'")
class
Project(TeamMember, TeamLeader):
def project_info(self):
print("This is the derived class 'Project'")
#
Demonstrate multiple inheritance
proj
= Project()
proj.team_member_info()
proj.team_leader_info()
proj.project_info()
3)
Python Program to Use `issubclass()` and `isinstance()` Functions
class
Animal:
pass
class
Dog(Animal):
pass
#
Check subclass relationship
print(issubclass(Dog,
Animal)) # True
#
Check instance relationship
dog
= Dog()
print(isinstance(dog,
Dog)) # True
print(isinstance(dog,
Animal)) # True
---
Set B
1)
Python Program Using Hybrid Inheritance (University and Course)
class
University:
def university_info(self):
print("This is the base class 'University'")
class
Course(University):
def course_info(self):
print("This is the derived class 'Course'")
class
Student(Course):
def student_info(self):
print("This is another derived class 'Student'")
#
Demonstrate hybrid inheritance
student
= Student()
student.university_info()
student.course_info()
student.student_info()
2)
Python Program Demonstrating Hierarchical Inheritance
class
Area:
def find_area(self):
print("This is the base class 'Area'")
class
Square(Area):
def find_area(self):
print("Area of Square")
class
Triangle(Area):
def find_area(self):
print("Area of Triangle")
#
Demonstrate hierarchical inheritance
sq =
Square()
sq.find_area()
tri
= Triangle()
tri.find_area()
3)
Python Program Defining `Shape` and Subclasses (Square/Circle)
class
Shape:
def area(self):
return 0
def volume(self):
return 0
class
Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return self.length 2
def volume(self):
return self.length 3
class
Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius 2
def volume(self):
return (4/3) * 3.14 * self.radius 3
#
Demonstrate area and volume calculation
sq =
Square(5)
print(f"Square
Area: {sq.area()}, Volume: {sq.volume()}")
cir
= Circle(4)
print(f"Circle
Area: {cir.area()}, Volume: {cir.volume()}")
4)
Python Program for `Country` and `State` Classes
class
Country:
def __init__(self, nationality):
self.nationality = nationality
def print_nationality(self):
print(f"Nationality: {self.nationality}")
class
State(Country):
def __init__(self, nationality, state):
super().__init__(nationality)
self.state = state
def print_state(self):
print(f"State: {self.state}")
#
Accept input and display results
country_obj
= State("Indian", "Maharashtra")
country_obj.print_nationality()
country_obj.print_state()
---
Set C
1)
Python Program Depicting Multiple Inheritance with Overridden Methods
class
ClassA:
def show(self):
print("Class A method")
class
ClassB:
def show(self):
print("Class B method")
class
ClassC(ClassA, ClassB):
def show(self):
super().show()
#
Demonstrate method overriding in multiple inheritance
obj
= ClassC()
obj.show()
# Output will depend on method resolution order (ClassA's method in this
case)
2)
Python Program Depicting HAS-A Relationship (Composition)
class
Engine:
def start(self):
print("Engine started")
class
Car:
def __init__(self):
self.engine = Engine() # Car has an engine
def start_car(self):
self.engine.start()
#
Demonstrate HAS-A relationship
car =
Car()
car.start_car()
Assignment 8
Practice Set
1.
Create a Window and Set Its Title
import
tkinter as tk
def
create_window():
window = tk.Tk()
window.title("My First Window")
window.geometry("300x200") # Set window size
window.mainloop()
create_window()
2.
Create Two Buttons (Exit and Hello)
import
tkinter as tk
def
on_hello():
print("Hello!")
window
= tk.Tk()
window.title("Buttons
Example")
hello_button
= tk.Button(window, text="Hello", command=on_hello)
exit_button
= tk.Button(window, text="Exit", command=window.quit)
hello_button.pack(pady=10)
exit_button.pack(pady=10)
window.mainloop()
3.
Create a Checkbutton and Three Text Boxes
import
tkinter as tk
def
on_check():
print(f"Checkbutton is {'checked' if check_var.get() else 'unchecked'}")
window
= tk.Tk()
window.title("Checkbutton
and Text Boxes")
check_var
= tk.IntVar()
check_button
= tk.Checkbutton(window, text="Check me", variable=check_var,
command=on_check)
check_button.pack()
entry1
= tk.Entry(window)
entry2
= tk.Entry(window)
entry3
= tk.Entry(window)
entry1.pack(pady=5)
entry2.pack(pady=5)
entry3.pack(pady=5)
window.mainloop()
4.
Create Three Radio Buttons
import
tkinter as tk
def
on_select(value):
print(f"Selected: {value}")
window
= tk.Tk()
window.title("Radio
Buttons Example")
radio_var
= tk.StringVar(value="Option 1")
for
option in ["Option 1", "Option 2", "Option 3"]:
tk.Radiobutton(window, text=option, variable=radio_var, value=option,
command=lambda: on_select(radio_var.get())).pack(anchor=tk.W)
window.mainloop()
5.
Create a Listbox Widget
import
tkinter as tk
def
add_item():
item = entry.get()
listbox.insert(tk.END, item)
window
= tk.Tk()
window.title("Listbox
Example")
entry
= tk.Entry(window)
entry.pack(pady=10)
add_button
= tk.Button(window, text="Add Item", command=add_item)
add_button.pack(pady=10)
listbox
= tk.Listbox(window)
listbox.pack(pady=10)
window.mainloop()
Set A
1.
Display an Alert Message When a Button is Pressed
import
tkinter as tk
from
tkinter import messagebox
def
show_alert():
messagebox.showinfo("Alert", "Button Pressed!")
window
= tk.Tk()
button
= tk.Button(window, text="Press Me", command=show_alert)
button.pack(pady=20)
window.mainloop()
2.
Create Background with Changing Colors
import
tkinter as tk
import
random
def
change_color():
colors = ["red", "green", "blue",
"yellow", "purple", "orange"]
window.config(bg=random.choice(colors))
window.after(1000, change_color) # Change color every second
window
= tk.Tk()
change_color()
window.mainloop()
3.
Create a Label and Change the Font Style
import
tkinter as tk
window
= tk.Tk()
label
= tk.Label(window, text="Hello, World!", font=("Helvetica",
16, "bold"))
label.pack(pady=20)
window.mainloop()
4.
Create a Text Widget and Manipulate Text
import
tkinter as tk
def
manipulate_text():
text_widget.insert("1.0", "Hello ")
text_widget.insert("end", "World!")
current_text = text_widget.get("1.0", "end-1c")
text_widget.delete("1.0")
text_widget.insert("1.0", current_text[1:-1]) # Delete
first and last character
window
= tk.Tk()
text_widget
= tk.Text(window, height=5, width=30)
text_widget.pack(pady=20)
manipulate_button
= tk.Button(window, text="Manipulate Text", command=manipulate_text)
manipulate_button.pack(pady=10)
window.mainloop()
5.
Accept Dimensions of a Cylinder and Display Surface Area and Volume
import
tkinter as tk
import
math
def
calculate_cylinder():
radius = float(radius_entry.get())
height = float(height_entry.get())
surface_area = 2 * math.pi * radius * (radius + height)
volume = math.pi * radius2 * height
result_label.config(text=f"Surface Area: {surface_area:.2f}\nVolume:
{volume:.2f}")
window
= tk.Tk()
window.title("Cylinder
Calculator")
radius_label
= tk.Label(window, text="Radius:")
radius_label.pack()
radius_entry
= tk.Entry(window)
radius_entry.pack()
height_label
= tk.Label(window, text="Height:")
height_label.pack()
height_entry
= tk.Entry(window)
height_entry.pack()
calculate_button
= tk.Button(window, text="Calculate", command=calculate_cylinder)
calculate_button.pack()
result_label
= tk.Label(window, text="")
result_label.pack()
window.mainloop()
6.
Change Input String to Upper Case When Button is Pressed
import
tkinter as tk
def
change_case():
input_text = entry.get()
result_label.config(text=input_text.upper())
window
= tk.Tk()
entry
= tk.Entry(window)
entry.pack(pady=10)
change_case_button
= tk.Button(window, text="Change to Upper Case", command=change_case)
change_case_button.pack(pady=10)
result_label
= tk.Label(window, text="")
result_label.pack()
window.mainloop()
Set B
1.
Input Date of Birth and Output Age
import
tkinter as tk
from
datetime import datetime
def
calculate_age():
dob = entry.get()
dob_date = datetime.strptime(dob, "%Y-%m-%d")
age = (datetime.now() - dob_date).days // 365
age_label.config(text=f"Age: {age}")
window
= tk.Tk()
entry
= tk.Entry(window)
entry.pack(pady=10)
calculate_button
= tk.Button(window, text="Calculate Age", command=calculate_age)
calculate_button.pack(pady=10)
age_label
= tk.Label(window, text="")
age_label.pack()
window.mainloop()
2.
Alter Sentence from User
import
tkinter as tk
def
alter_sentence():
sentence = entry.get()
altered = sentence.replace(" ", "*")[::-1] #
Replace spaces and reverse case
result_label.config(text=altered)
window
= tk.Tk()
entry
= tk.Entry(window)
entry.pack(pady=10)
alter_button
= tk.Button(window, text="Alter Sentence", command=alter_sentence)
alter_button.pack(pady=10)
result_label
= tk.Label(window, text="")
result_label.pack()
window.mainloop()
3.
Create a Digital Clock
import
tkinter as tk
import
time
def
update_clock():
current_time = time.strftime("%H:%M:%S")
clock_label.config(text=current_time)
window.after(1000, update_clock)
window
= tk.Tk()
clock_label
= tk.Label(window, font=("Helvetica", 48))
clock_label.pack()
update_clock()
window.mainloop()
4.
Generate Random Password
import
tkinter as tk
import
random
import
string
def
generate_password():
length = 10
characters = string.ascii_letters + string.digits
password = ''.join(random.choice(characters) for i in range(length))
password_label.config(text=f"Password: {password}")
window
= tk.Tk()
generate_button
= tk.Button(window, text="Generate Password",
command=generate_password)
generate_button.pack(pady=10)
password_label
= tk.Label(window, text="")
password_label.pack()
window.mainloop()
5.
Display Each Digit of a Number in Words
import
tkinter as tk
def
number_to_words(num):
words = {0: "Zero", 1: "One", 2: "Two", 3:
"Three", 4: "Four",
5: "Five", 6:
"Six", 7: "Seven", 8: "Eight", 9:
"Nine"}
return ' '.join(words[int(digit)] for digit in str(num))
def
display_digits():
num = entry.get()
result_label.config(text=number_to_words(num))
window
= tk.Tk()
entry
= tk.Entry(window)
entry.pack(pady=10)
convert_button
= tk.Button(window, text="Convert to Words", command=display_digits)
convert_button.pack(pady=10)
result_label
= tk.Label(window, text="")
result_label.pack()
window.mainloop()
6. Convert Decimal Number to Binary, Octal, and Hexadecimal
import tkinter as tk
def
convert_number():
decimal = int(entry.get())
binary = bin(decimal)[2:] # Remove '0b'
octal = oct(decimal)[2:] # Remove '0o'
hexadecimal = hex(decimal)[2:].upper() # Remove '0x' and convert
to uppercase
result_label.config(text=f"Binary: {binary}\nOctal: {octal}\n
Hexadecimal: {hexadecimal}")
window
= tk.Tk()
entry
= tk.Entry(window)
entry.pack(pady=10)
convert_button
= tk.Button(window, text="Convert", command=convert_number)
convert_button.pack(pady=10)
result_label
= tk.Label(window, text="")
result_label.pack()
window.mainloop()
7. Add Items in Listbox and Print/Delete Selected Items
import tkinter as tk
def add_item():
item = entry.get()
listbox.insert(tk.END, item)
def print_selected():
selected = listbox.curselection()
for index in selected:
print(listbox.get(index))
def delete_selected():
selected = listbox.curselection()
for index in selected[::-1]: # Delete from the end to avoid index
issues
listbox.delete(index)
window
= tk.Tk()
entry
= tk.Entry(window)
entry.pack(pady=10)
add_button
= tk.Button(window, text="Add Item", command=add_item)
add_button.pack(pady=10)
listbox
= tk.Listbox(window)
listbox.pack(pady=10)
print_button
= tk.Button(window, text="Print Selected", command=print_selected)
print_button.pack(pady=5)
delete_button
= tk.Button(window, text="Delete Selected", command=delete_selected)
delete_button.pack(pady=5)
window.mainloop()
8.
Menu Bar to Change Background Color
import tkinter as tk
def change_color(color):
window.config(bg=color)
window
= tk.Tk()
menu_bar = tk.Menu(window)
colors
= ["red", "green", "blue", "yellow", "purple",
"orange"]
for
color in colors:
menu_bar.add_command(label=color, command=lambda c=color: change_color(c))
window.config(menu=menu_bar)
window.mainloop()
9.
Check Whether Number is Prime, Perfect, or Armstrong
import
tkinter as tk
def check_number():
number = int(entry.get())
is_prime = all(number % i != 0 for i in range(2, int(number0.5) + 1)) if
number > 1 else False
result_label.config(text=f"Prime: {is_prime}")
window
= tk.Tk()
entry
= tk.Entry(window)
entry.pack(pady=10)
check_button
= tk.Button(window, text="Check Number", command=check_number)
check_button.pack(pady=10)
result_label
= tk.Label(window, text="")
result_label.pack()
window.mainloop()
10.
Change Label Font Style with Checkbuttons
import tkinter as tk
def update_label_style():
font_style = ""
if bold_var.get():
font_style += "bold "
if italic_var.get():
font_style += "italic "
label.config(font=("Helvetica", 12, font_style.strip()))
window
= tk.Tk()
label
= tk.Label(window, text="Sample Text")
label.pack(pady=20)
bold_var
= tk.BooleanVar()
italic_var = tk.BooleanVar()
bold_check
= tk.Checkbutton(window, text="Bold", variable=bold_var, command=update_label_style)
italic_check = tk.Checkbutton(window, text="Italic", variable=italic_var, command=update_label_style)
bold_check.pack()
italic_check.pack()
window.mainloop()
Set C
1. Implement Simple Calculator
import tkinter as tk
def calculate():
try:
result = eval(entry.get())
result_label.config(text=f"Result: {result}")
except Exception as e:
result_label.config(text="Error")
window
= tk.Tk()
entry
= tk.Entry(window)
entry.pack(pady=10)
calculate_button
= tk.Button(window, text="Calculate", command=calculate)
calculate_button.pack(pady=10)
result_label
= tk.Label(window, text="")
result_label.pack()
window.mainloop()