PY Assignment 2
PY Assignment 2
Ans:
-The following program demonstrates basic set operations like adding elements, removing elements, and
performing union and intersection:
-Example:-
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set1.add(6)
print("Set after adding an element:", set1)
set1.remove(3)
print("Set after removing an element:", set1)
union_set = set1.union(set2)
print("Union of sets:", union_set)
intersection_set = set1.intersection(set2)
print("Intersection of sets:", intersection_set)
-Example:
num = int(input("Enter a number: "))
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Creation: A tuple is created using parentheses `()` and separating elements with commas:
eg.
my_tuple = (1, 2, 3, "Python")
Accessing Elements: Elements in a tuple can be accessed using indexing, just like lists:
eg.
print(my_tuple[0])
print(my_tuple[3])
Q6: List and explain any four built-in string manipulation functions supported by
Python.
Ans:
-Python provides various built-in functions to manipulate strings.
-Here are four commonly used ones:
1. `uppe – Converts all characters of a string to uppercase.
Eg.,
text = "hello"
print(text.upper()) # Output: HELLO
2. `lower()` – Converts all characters of a string to lowercase.
Eg.,
text = "HELLO"
print(text.lower()) # Output: hello
-Example:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input, please enter a number.")