Python exps questions
Python exps questions
contacts = {}
def remove_contact(name):
if name in contacts:
del contacts[name]
def show_contacts():
for name, phone in contacts.items():
print(name, phone)
# Example usage
add_contact("Alice", "1234567890")
add_contact("Bob", "9876543210")
show_contacts()
update_contact("Bob", "1112223333")
search_contact("Bob")
remove_contact("Alice")
show_contacts()
file_name = 'sample.txt'
data_to_append = "\nThis is some new data to append to the file."
print(content)
file_name = 'sample.txt'
with open(file_name, 'r') as file:
lines = file.readlines()
num_lines = len(lines)
num_words = sum(len(line.split()) for line in lines)
num_chars = sum(len(line) for line in lines)
import os
files = os.listdir(os.getcwd())
import numpy as np
Output:
NumPy Array: [1 2 3 4 5]
import numpy as np
zeros_array = np.zeros((3,3))
ones_array = np.ones((2,2))
identity_matrix = np.eye(3)
Output:
Element at index 2: 30
reshaped_arr = arr.reshape(2, 3)
Output:
Reshaped Array:
[[1 2 3]
[4 5 6]]
# Element-wise addition
# Element-wise multiplication
# Mean of an array
print("Mean:", np.mean(arr1))
import numpy as np
# Creating a 1D array
# Creating a 2D array
# Creating a 3D array
Output:
1D Array: [1 2 3 4 5]
2D Array:
[[1 2 3]
[4 5 6]]
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
10) Indexing and Slicing Arrays
# Indexing
# Slicing
Output:
Slice of arr1: [2 3 4]
reshaped_arr = arr1.reshape(5, 1)
# Flattening a 2D array to 1D
flattened_arr = arr2.flatten()
Reshaped Array:
[[1]
[2]
[3]
[4]
[5]]
Flattened Array: [1 2 3 4 5 6]
Output:
Subtraction: [ 9 18 27 36]
import pandas as pd
series = pd.Series(data)
Output:
Pandas Series:
0 10
1 20
2 30
3 40
4 50
dtype: int64
import pandas as pd
df = pd.DataFrame(data)
print("Pandas DataFrame:\n", df)
Output:
Pandas DataFrame:
2 Charlie 35 Chicago
# Filtering Data