R23 Mech Python
R23 Mech Python
Output:
Hello, World!
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.3333333333333335 (float division)
print(a // b) # Integer division: 3
print(a % b) # Modulus: 1
print(a ** b) # Exponentiation: 1000
Output:
13
7
30
3.3333333333333335
3
1
1000
output:
6 <class 'int'>
4.13 <class 'float'>
CIST <class 'str'>
True <class 'bool'>
Program:
# Conditional logic using if-else statements
num = 5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output:
Positive number
Output:
0
1
2
3
4
Output:
0
1
2
3
4
Program:
# Defining and calling a function
def greet(name):
return f"Hello, {name}!"
print(greet("CIST"))
Output:
Hello, CIST!
Program:
def add(x,y):
return x+y
print(add(5,4))
Output:
9
Program:
# Pause execution for a random number of seconds (using the random number generated)
print(f"Waiting for {random_number} seconds...")
time.sleep(random_number)
Output:
Random Number: 9
Current Date and Time: 2024-9-18 15:44:26.994288
Waiting for 9 seconds...
Done! Waited for 9 seconds.
Program:
# Create a list
my_list = [10, 20, 30, 40, 50]
print("Original List:", my_list)
# Create a tuple
my_tuple = (1, 2, 3, 4, 5)
print("\nOriginal Tuple:", my_tuple)
# Tuples are immutable, so we cannot modify them directly. However, we can create a new tuple.
new_tuple = my_tuple + (6,) # Adding an element to a tuple (creates a new tuple)
print("Modified Tuple (new tuple created):", new_tuple)
Output:
Original List: [10, 20, 30, 40, 50]
Modified List: [10, 20, 100, 50, 60]
Iterating over the list:
10
20
100
50
60
Output:
Squares: [1, 4, 9, 16, 25]
Program:
# Example 2: Create a list of even numbers using list comprehension
even_numbers = [x for x in numbers if x % 2 == 0]
print("Even Numbers:", even_numbers)
OutPut:
Even Numbers: [2, 4]
Output:
Number-Square Tuples: [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
Output:
Vowels in string: ['e', 'o', 'o']
# Example 5: Create a list of numbers that are divisible by both 2 and 3 using list comprehension
div_by_2_and_3 = [x for x in range(1, 21) if x % 2 == 0 and x % 3 == 0]
print("Numbers divisible by 2 and 3:", div_by_2_and_3)
Output:
Numbers divisible by 2 and 3: [6, 12, 18]
# Tuples are immutable, so we cannot add elements directly, but we can create a new tuple
new_tuple = my_tuple + (40, 50) # Concatenate a new tuple
print("New Tuple after concatenation:", new_tuple)
Output:
ERROR!
Original Tuple: (10, 20, 30)
Error: 'tuple' object does not support item assignment
Tuple after trying to modify: (10, 20, 30)
New Tuple after concatenation: (10, 20, 30, 40, 50)
ERROR!
Error: 'tuple' object doesn't support item deletion
Tuple after trying to delete an element: (10, 20, 30)
Output:
Original Dictionary: {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'grade': 'A'}
Student Name: Alice
Student Major: Computer Science
Dictionary after adding 'graduation_year': {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'grade':
'A', 'graduation_year': 2024}
Dictionary after modifying 'grade': {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'grade': 'A+',
'graduation_year': 2024}
Dictionary after removing 'major': {'name': 'Alice', 'age': 22, 'grade': 'A+', 'graduation_year': 2024}
Removed Major: Computer Science
Age is present in the dictionary.
# 3. Filter a dictionary using dictionary comprehension (only keep even numbers and their squares)
original_dict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
even_squares_dict = {k: v for k, v in original_dict.items() if k % 2 == 0}
print("Filtered Dictionary (only even numbers):", even_squares_dict)
# 4. Create a dictionary where the keys are numbers and values are whether they are odd or even
odd_even_dict = {x: ('even' if x % 2 == 0 else 'odd') for x in range(1, 6)}
print("Odd/Even Dictionary:", odd_even_dict)
Output:
Dictionary of squares: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Student Dictionary: {'name': 'Alice', 'age': 22, 'major': 'Computer Science'}
Filtered Dictionary (only even numbers): {2: 4, 4: 16}
Odd/Even Dictionary: {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}
- Create and perform operations on sets.
Output:
# 1. Creating sets
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
print("Set A:", set_a)
print("Set B:", set_b)
# 5. Set Union
union_set = set_a.union(set_b) # OR set_a | set_b
print("Union of Set A and Set B:", union_set)
# 6. Set Intersection
intersection_set = set_a.intersection(set_b) # OR set_a & set_b
print("Intersection of Set A and Set B:", intersection_set)
# 8. Set Symmetric Difference (elements in either set_a or set_b but not both)
symmetric_difference_set = set_a.symmetric_difference(set_b) # OR set_a ^ set_b
print("Symmetric Difference of Set A and Set B:", symmetric_difference_set)
# 9. Checking for subset and superset relationships
set_c = {4, 5}
print("Set C is a subset of Set A:", set_c.issubset(set_a)) # True if set_c is a subset of set_a
print("Set A is a superset of Set C:", set_a.issuperset(set_c)) # True if set_a is a superset of set_c
Output:
Set A: {1, 2, 3, 4, 5}
Set B: {4, 5, 6, 7, 8}
Set A after adding 6: {1, 2, 3, 4, 5, 6}
Set A after removing 2: {1, 3, 4, 5, 6}
Set A after discarding 10 (non-existent): {1, 3, 4, 5, 6}
Union of Set A and Set B: {1, 3, 4, 5, 6, 7, 8}
Intersection of Set A and Set B: {4, 5, 6}
Difference of Set A and Set B (A - B): {1, 3}
Symmetric Difference of Set A and Set B: {1, 3, 7, 8}
Set C is a subset of Set A: True
Set A is a superset of Set C: True
Set A and Set B are disjoint: True
Output:
Uppercase: HELLO, WORLD!
Lowercase: hello, world!
Stripped: Hello, World!
Replaced 'World' with 'Python': Hello, Python!
Split: ['Hello,', 'World!']
Joined: Hello Python World
Index of 'World': 9
Count of 'l': 3
Starts with 'Hello': False
Ends with 'World!': False
Is alphabetic: False
Is digit: True
Title case: Hello, World!
Capitalized: hello, world!
Last index of 'l': 12
Program:
# Program to write to a text file
# Data to write to the file
data = """Hello, World!
This is a sample text file.
Python makes file handling easy!"""
# Open the file in write mode
with open("sample.txt", "w") as file:
# Write the data to the file
file.write(data)
print("Data has been written to sample.txt")
Output:
Hello, World!
This is a sample text file.
Python makes file handling easy!
python
Copy code
import csv
Output
Data has been written to 'people.csv'.
Content of 'people.csv':
['Name', 'Age', 'City']
['Alice', '28', 'New York']
['Bob', '23', 'Los Angeles']
['Charlie', '35', 'Chicago']
python
Copy code
import json
print("\nContent of 'employees.json':")
print(json.dumps(loaded_data, indent=4))
Output
Data has been written to 'employees.json'.
Content of 'employees.json':
{
"employees": [
{
"name": "Alice",
"age": 28,
"city": "New York"
},
{
"name": "Bob",
"age": 23,
"city": "Los Angeles"
},
{
"name": "Charlie",
"age": 35,
"city": "Chicago"
}
]
}
# Test cases
print("Test case 1:")
divide_numbers(10, 2)
Output:
Test case 1:
ERROR!
Result: 10 / 2 = 5.0
Execution of division completed.
Test case 2:
Error: Division by zero is not allowed.
Execution of division completed.
def divide_numbers():
try:
# Take two inputs from the user and try to divide them
a = int(input("Enter the numerator: "))
b = int(input("Enter the denominator: "))
result = a / b
except ZeroDivisionError:
# Handle the case where division by zero is attempted
print("Error: Division by zero is not allowed.")
except ValueError:
# Handle the case where the input is not a valid integer
print("Error: Please enter valid integers.")
else:
# No exception occurred, print the result
print(f"Result: {a} / {b} = {result}")
finally:
# This will always execute, regardless of exceptions
print("Execution completed.")
Output: