HP2
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error! Division by zero is not allowed."
return a / b
Dictionary to act like switch case
def calculator(a, b, choice):
switch = {
1: add,
2: subtract,
3: multiply,
4: divide
}
operation = switch.get(choice)
if operation:
result = operation(a, b)
print("Result:", result)
else:
print("Invalid choice! Please select between 1 and 4.")
Taking user input
print("Choose an operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = int(input("Enter your choice (1-4): "))
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
calculator(a, b, choice)
...............
first = int(input("Enter first number: "))
second = int(input("Enter second number: "))
sum = first + second
if(sum > 100):
print("Sum exceeds 100")
elif(sum == 100):
print("Sum is exactly 100")
else:
print("Sum is less than 100")
..........................
num = int(input("Enter a number: "))
for num in range(1,num+1):
print("Numbers are: ", num)
..........................FACTORIAL
num = int(input("Enter a number: "))
if num < 0:
print("Factorial for nageative number is not defined")
else:
i = 1
factorialAns = 1
while i <= num:
factorialAns = factorialAns * i
i += 1
print("Factorial is: ", factorialAns)
............................STRING
def string_operations(s):
# i. Convert to uppercase
upper_str = s.upper()
print("Uppercase:", upper_str)
# ii. Reverse the string
reversed_str = s[::-1]
print("Reversed:", reversed_str)
# iii. Check for palindrome (ignoring case)
is_palindrome = s.lower() == s[::-1].lower()
print("Is Palindrome:", is_palindrome)
# Returning values in case you want to use them programmatically
return upper_str, reversed_str, is_palindrome
Example usage:
input_str = input("Enter a string: ")
string_operations(input_str)
...........................CLASS
class MathOperations:
def init(self, x, y):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def multiply(self):
return self.x * self.y
Create an instance of MathOperations
first = int(input("Enter first number: "))
second = int(input("Enter second number: "))
math_op = MathOperations(first, second)
Call the add and multiply methods
print("Sum:", math_op.add()) # Output: Sum: 8
print("Product:", math_op.multiply()) # Output: Product: 15
.................................LIST
Python Program to demonstrate various List methods
Creating a list
fruits = ['apple', 'banana', 'cherry']
print("Original List:", fruits)
Length of the list
print("Length of list:", len(fruits))
Insert an element at a specific position
fruits.insert(1, 'orange') # Inserts 'orange' at index 1
print("After insert:", fruits)
Append an element to the end
fruits.append('mango')
print("After append:", fruits)
Extend the list with another list
more_fruits = ['grape', 'pineapple']
fruits.extend(more_fruits)
print("After extend:", fruits)
Remove a specific element
fruits.remove('banana') # Removes the first occurrence of 'banana'
print("After remove:", fruits)
Pop the last element (or specific index)
popped_item = fruits.pop()
print("Popped item:", popped_item)
print("After pop:", fruits)
Delete an element by index
del fruits[2] # Deletes the item at index 2
print("After delete:", fruits)
Copy the list
fruits_copy = fruits.copy()
print("Copied list:", fruits_copy)
Sort the list
fruits.sort()
print("After sort:", fruits)
Reverse the list
fruits.reverse()
print("After reverse:", fruits)
Clear the list
fruits.clear()
print("After clear:", fruits)
Join two lists
list1 = ['a', 'b', 'c']
list2 = ['d', 'e']
joined_list = list1 + list2
print("Joined list:", joined_list)
..........................TUPLE
Python Program to demonstrate Tuple operations
1. Creating tuples
tuple1 = (10, 20, 30, 40)
tuple2 = ('a', 'b', 'c')
Display original tuples
print("Tuple 1:", tuple1)
print("Tuple 2:", tuple2)
2. Length of a tuple
print("\nLength of Tuple 1:", len(tuple1))
print("Length of Tuple 2:", len(tuple2))
3. Copying a tuple
Tuples are immutable, so copying is straightforward
tuple_copy = tuple1
print("\nCopied Tuple:", tuple_copy)
4. Joining (concatenating) tuples
joined_tuple = tuple1 + tuple2
print("\nJoined Tuple:", joined_tuple)
5. Nested Tuple
nested_tuple = (tuple1, tuple2)
print("\nNested Tuple:", nested_tuple)
6. Tuple repetition
repeated_tuple = tuple2 * 2
print("\nRepeated Tuple:", repeated_tuple)
..................DICTIONARY
Python Program to demonstrate various Dictionary operations
1. Creating a dictionary
student = {
"name": "Manasvi",
"age": 21,
"course": "BTech",
"university": "Bharati Vidyapeeth"
}
print("Initial Dictionary:")
print(student)
2. Length of dictionary
print("\nLength of Dictionary:", len(student))
3. Getting all keys
print("\nKeys in Dictionary:", student.keys())
4. Adding a new key-value pair
student["year"] = 3
print("\nAfter Adding New Pair (year):")
print(student)
5. Updating values
student["age"] = 22
print("\nAfter Updating 'age' value:")
print(student)
6. Listing all items (key-value pairs)
print("\nAll Items in Dictionary:")
for key, value in student.items():
print(f"{key}: {value}")
7. Popping a value
popped_value = student.pop("course")
print(f"\nAfter Popping 'course' (value was: {popped_value}):")
print(student)
8. Deleting a key-value pair
del student["university"]
print("\nAfter Deleting 'university':")
print(student)
9. Copying a dictionary
student_copy = student.copy()
print("\nCopied Dictionary:")
print(student_copy)
10. Joining two dictionaries
extra_info = {"hobby": "Coding", "city": "Pune"}
Method 1: Using update()
student.update(extra_info)
print("\nAfter Joining with extra_info using update():")
print(student)
Method 2: Using dictionary unpacking (Python 3.5+)
joined_dict = {**student_copy, **extra_info}
print("\nJoining using dictionary unpacking:")
print(joined_dict)
...................................SET
Python program to demonstrate various methods of Set
Creating a set
my_set = {1, 2, 3, 4}
print("Original Set:", my_set)
Length of set
print("Length of Set:", len(my_set))
Add an element
my_set.add(5)
print("After add(5):", my_set)
Update set with multiple elements
my_set.update([6, 7, 8])
print("After update([6, 7, 8]):", my_set)
Remove an element (throws error if element not found)
my_set.remove(8)
print("After remove(8):", my_set)
Discard an element (does not throw error if element not found)
my_set.discard(10) # 10 is not in the set
print("After discard(10):", my_set)
Pop an element (removes and returns an arbitrary element)
popped = my_set.pop()
print(f"After pop(): {popped} was removed, New Set: {my_set}")
Copying the set before clearing for delete demo
copy_set = my_set.copy()
Clear all elements from the set
my_set.clear()
print("After clear():", my_set)
Delete the set completely
del copy_set
print("Set deleted successfully (copy_set)")
Demonstrating union
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print("Union of set1 and set2:", union_set)
Demonstrating intersection
intersection_set = set1.intersection(set2)
print("Intersection of set1 and set2:", intersection_set)
Demonstrating intersection_update
set3 = {2, 3, 4}
set4 = {3, 4, 5}
set3.intersection_update(set4)
print("After intersection_update, set3:", set3)
.......................