0% found this document useful (0 votes)
22 views31 pages

python 8m-1-31

The document provides a comprehensive overview of Python programming concepts, including basic data types, function definitions, return statements, membership operators, lists vs. tuples, access modifiers, file handling, method overriding, CSV file handling, JSON features, built-in functions, string manipulation, dictionaries, and inheritance types. Each section includes explanations, syntax, and example code to illustrate the concepts. The document serves as a guide for understanding and implementing various Python functionalities.

Uploaded by

av5bkc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views31 pages

python 8m-1-31

The document provides a comprehensive overview of Python programming concepts, including basic data types, function definitions, return statements, membership operators, lists vs. tuples, access modifiers, file handling, method overriding, CSV file handling, JSON features, built-in functions, string manipulation, dictionaries, and inheritance types. Each section includes explanations, syntax, and example code to illustrate the concepts. The document serves as a guide for understanding and implementing various Python functionalities.

Uploaded by

av5bkc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

1.a) Write a python program to demonstrate basic data types.

 Below is a Python program that demonstrates the basic data types in Python, including integers,
floats, strings, booleans, lists, tuples, sets, and dictionaries.
# Demonstrating Basic Data Types in Python

# Integer
integer_value = 10
print("Integer:", integer_value)

# Float
float_value = 20.5
print("Float:", float_value)

# String
string_value = "Hello, Python!"
print("String:", string_value)

# Boolean
boolean_value = True
print("Boolean:", boolean_value)

# List
list_value = [1, 2, 3, "Python", True]
print("List:", list_value)

# Dictionary
dict_value = {"name": "Alice", "age": 25}
print("Dictionary:", dict_value)
b.Explain function definition and function call with examples
 Function Definition: This is where the function is created. It specifies the name, parameters (if
any), and the block of code that the function will execute when called.
Some Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability

Python Function Declaration

 Function Call: This is where the function is invoked or used,


executing the block of code defined within the function.

Complete Example:

def add(a, b):


return a + b

# Calling the function


result = add(5, 3)
print(f"The sum is: {result}") # Output: The sum is: 8
2. a) Explain the purpose of "return" statement in python.
 A return statement is used to end the execution of the function call and “returns” the result to
the caller.
 The statements after the return statements are not executed.
 If the return statement is without any expression, then the special value None is returned.
 A return statement is overall used to invoke a function so that the passed statements can be
executed.
Note: Return statement can not be used outside the function.
Syntax:
def fun():
statements
.
.
return [expression]
Example:
def cube(x):
r=x**3
return r
b) Write a program to accept the radius of a circle from user and compute the area.
Here is a Python program that accepts the radius of a circle from the user and computes its area:
import math

# Accept the radius of a circle from the user


radius = float(input("Enter the radius of the circle: "))

# Calculate the area of the circle


area = math.pi * radius**2

# Display the result


print(f"The area of the circle with radius {radius} is {area:.2f}")
3 .a) How membership operators (in and not in) works with a dictionary?
 In Python, membership operators (in and not in) can be used with dictionaries to test for the
presence or absence of keys.
 They do not directly check for values or key-value pairs unless explicitly specified.
How They Work with Dictionaries:
in Operator:
 Returns True if the specified key exists in the dictionary.
 Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print('a' in my_dict) # True
print('x' in my_dict) # False
not in Operator:
 Returns True if the specified key does not exist in the dictionary.
 Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print('x' not in my_dict) # True
print('a' not in my_dict) # False

Key Points
 Both operators only check for keys, not values.
 They are efficient and provide a straightforward way to verify key existence.
 These operators can be used in conditional statements to control the flow of the program based
on key presence.
b) Differentiate between Lists and Tuples.

Sno LIST TUPLE

1 Lists are mutable Tuples are immutable

The implication of iterations is


2 The implication of iterations is Time-consuming
comparatively Faster

The list is better for performing operations, such as A Tuple data type is appropriate for
3
insertion and deletion. accessing the elements

Tuple consumes less memory as


4 Lists consume more memory
compared to the list

Tuple does not have many built-in


5 Lists have several built-in methods
methods.

Unexpected changes and errors are more likely to Because tuples don’t change they are far
6
occur less error-prone.

4. a) Explain access modifiers in python.


 Access modifiers in Python define the level of accessibility or visibility of class members
(attributes and methods).
 They control how and where a class's variables and methods can be accessed. Python provides
three levels of access modifiers:
1. Public
 Syntax: Normal variable or method names, e.g., self.variable_name.
 Accessibility: Public members can be accessed from anywhere: within the class, derived classes,
and outside the class.
2. Protected
 Syntax: Prefix with a single underscore, e.g., _variable_name.
 Accessibility: Protected members are intended to be accessible within the class and its
subclasses. By convention, they should not be accessed outside the class, although Python
doesn't enforce this restriction.
3. Private
 Syntax: Prefix with a double underscore, e.g., __variable_name.

 Accessibility: Private members are only accessible within the class where they are defined. They
are name-mangled to prevent direct access from outside the class or its subclasses.

b) Explain the steps to create and read a text file in python.

Creating a Text File

1. Open the File in Write Mode:


o Use the open() function with the mode 'w' to create a new file or overwrite an existing
one.
2. Write Content to the File:
o Use the write() method to add content to the file.
3. Close the File:
o Always close the file using the close() method to ensure the data is saved and resources
are freed.

File Reading Process


 Open the File: Use the open() function to open a file. You need to specify the file name and the
mode
 Read the File: Use methods like .read(), .readline(), or .readlines() to read the contents of the
file.
 Close the File: Use the .close() method to close the file after you're done.
EXAMPLE
# Create a file and write content
with open("example.txt", "w") as file:
file.write("Hello, this is a sample text file.\n")
file.write("Python makes file handling easy!")

# Read the file content


with open("example.txt", "r") as file:
content = file.read()
print(content)
5. a) Explain method overriding with an example.
 Method overriding is a feature in object-oriented programming that allows a subclass to
provide a specific implementation of a method that is already defined in its parent class.
 The method in the child class must have the same name and parameters as the method in the
parent class.
 It allows dynamic (runtime) polymorphism.
EXAMPLE:
class Animal:
def speak(self):
return "Animal makes a sound"

class Dog(Animal):
def speak(self):
return "Dog barks"

class Cat(Animal):
def speak(self):
return "Cat meows"

# Test the behavior


animal = Animal()
dog = Dog()
cat = Cat()

print(animal.speak()) # Output: Animal makes a sound


print(dog.speak()) # Output: Dog barks
print(cat.speak()) # Output: Cat meows
b) Discuss the concept of CSV files in python.
 CSV (Comma-Separated Values) files are widely used in Python for data storage and exchange.
 They store tabular data in plain text format, where each line represents a data record, and fields
are separated by a delimiter, typically a comma.
 Python provides built-in and third-party tools for working with CSV files.
Features of CSV Files

1. Plain Text Format: Easily readable and editable in text editors.


2. Tabular Data Representation: Suitable for storing rows and columns.
3. Delimiters: Default delimiter is a comma, but other delimiters (e.g., tab, semicolon) can also
be used.
4. Compatibility: Supported by spreadsheets and many other tools for data processing.
Advantages
 Lightweight and human-readable format.
 No complex structure, easy to process programmatically.
 Supported by most programming languages and tools.
6.a) What are the features of JSON?
 JSON (JavaScript Object Notation) is widely used in Python for data interchange.
 Python too supports JSON with a built-in package called JSON.
1. Serialization (Encoding)
 Converts Python objects into JSON strings.
 Supported Python objects for conversion:
dict -> JSON object
list, tuple -> JSON array
str -> JSON string
int, float -> JSON number
True -> true, False -> false, None -> null
2. Deserialization (Decoding)
 Converts JSON strings back into Python objects.
3. Error Handling
 Provides exceptions like JSONDecodeError to handle invalid JSON formats.
4. Compact Encoding
 Default JSON serialization produces compact output.
 You can disable spaces for more compact representations:
5. Pretty Printing
 The indent parameter formats JSON for readability.
b) Explain the plot() method parameters for customizing a line graph.
 In Python, the plot() method is primarily used in the matplotlib.pyplot module to create line
graphs.
 This method offers various parameters to customize the appearance and behavior of the graph.
 These parameters include linestyle, which allows you to change the style of the line, such as
solid, dashed, or dotted.
 You can also customize the line color using the color parameter.
EXAMPLE:
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

plt.plot(x, y, linestyle='--', color='red', linewidth=2, marker='o', markeredgecolor='black',


markerfacecolor='blue', label='Line 1')

plt.legend()
plt.show()
7.a) Explain the various built - in functions in python with their syntax and example.
 Python provides a wide range of built-in functions that simplify programming tasks.
 These functions can perform operations related to data types, mathematics, input/output, and
more.
1. len()
 Purpose: Returns the number of elements in the tuple.
 Syntax: len(s)
 Usage:
my_tuple = (1, 2, 3, 4)
print(len(my_tuple)) # Output: 4
2. max()
 Purpose: Returns the largest item in the tuple.
 Syntax: max(iterable, *[, key])
 Usage:
my_tuple = (1, 5, 3, 9)
print(max(my_tuple)) # Output: 9
3. min()
 Purpose: Returns the smallest item in the tuple.
 Syntax: min(iterable, *[, key])
 Usage:
my_tuple = (1, 5, 3, 9)
print(min(my_tuple)) # Output: 1
4. sum()
 Purpose: Calculates the sum of all elements in the tuple.
 Syntax: sum(iterable, start=0)
 Usage:
my_tuple = (1, 2, 3, 4)
print(sum(my_tuple)) # Output: 10
5.float(): Converts a value to a floating-point number.
 Syntax: float(x)
 Example:
print(float("3.14")) # Outputs: 3.14
6.abs(): Returns the absolute value of a number.
 Syntax: abs(x)
 Example: print(abs(-5))
b) Write a python program to print a number is positive or negative.
# Program to check if a number is positive, negative, or zero

# Input from the user


number = float(input("Enter a number: "))

# Check if the number is positive, negative, or zero


if number > 0:
print(f"The number {number} is positive.")
elif number < 0:
print(f"The number {number} is negative.")
else:
print("The number is zero.")
8. Explain the concepts of string creating, slicing, comparing and finding sub-string in python with an
example.
1. Creating Strings
 Strings in Python can be created using single, double, or triple quotes.
# Examples of string creation
string1 = 'Hello'
string2 = "World"
string3 = '''This is a multiline
string.'''
print(string1) # Output: Hello
print(string2) # Output: World
print(string3)
2.String Slicing in Python
 String slicing in Python is a way to get specific parts of a string by using start, end, and step
values.
 It’s especially useful for text manipulation and data parsing.

 Syntax -
substring = s[start : end : step]

 Ex-
s = "Hello, Python!"

s2 = s[0:5]

print(s2)

3. Comparing Strings

 String comparison checks if two strings are equal or how they relate lexicographically
(alphabetical order). Python uses comparison operators like ==, !=, <, >, <=, and >=.

str1 = "apple"

str2 = "banana"

str3 = "apple
# Comparisons
print(str1 == str3) # Output: True (they are equal)
print(str1 < str2) # Output: True ('apple' comes before 'banana')
print(str1 != str2) # Output: True (they are not equal)
4. Finding Substring
 You can find the position of a substring within a string using the find() method. It returns the
lowest index of the substring if found, otherwise it returns -1.
Ex:
# Finding a substring
my_string = "Hello, World!"
position = my_string.find("World") # Finds the index of "World"
print(position) # Output: 7

# If the substring is not found


not_found_position = my_string.find("Python")
print(not_found_position) # Output: -1
9. What is a dictionary? Write a python program to create a dictionary and
a. print the dictionary items.
b. use get ()
 A dictionary in Python is a built-in data type that allows you to store data in key-value pairs.
 Each key is unique and is used to access its corresponding value.
 Dictionaries are mutable, meaning you can change their content after creation.

Example Python Program:


# Creating a dictionary
my_dict = {
'name': 'Alice',
'age': 30,
'city': 'New York',
'occupation': 'Engineer'
}

# a. Print the dictionary items


print("Dictionary items:")
for key, value in my_dict.items():
print(f"{key}: {value}")

# b. Use get()
# Using get() to access a value
age = my_dict.get('age')
print(f"\nUsing get() to access age: {age}")

# Using get() with a default value


country = my_dict.get('country', 'Not specified')
print(f"Using get() to access country: {country}")
10. What is inheritance? Explain the different types of inheritance in python with an example.
 Inheritance is a fundamental concept in object-oriented programming that allows a class (child
class) to inherit properties and behaviors (attributes and methods) from another class (parent
class).
Single Inheritance
class Parent:
def show(self):
print("This is the parent class")

class Child(Parent):
def display(self):
print("This is the child class")

obj = Child()
obj.show() # Accessing parent class method
obj.display() # Accessing child class method
Multiple Inheritance
class Parent1:
def method1(self):
print("This is Parent1")

class Parent2:
def method2(self):
print("This is Parent2")

class Child(Parent1, Parent2):


def method3(self):
print("This is the child class")

obj = Child()
obj.method1()
obj.method2()
obj.method3()
Multilevel Inheritance
class Grandparent:
def method1(self):
print("This is the grandparent class")

class Parent(Grandparent):
def method2(self):
print("This is the parent class")

class Child(Parent):
def method3(self):
print("This is the child class")

obj = Child()
obj.method1()
obj.method2()
obj.method3()
Hierarchical Inheritance
class Parent:
def method(self):
print("This is the parent class")

class Child1(Parent):
def method1(self):
print("This is child class 1")

class Child2(Parent):
def method2(self):
print("This is child class 2")

obj1 = Child1()
obj1.method()
obj1.method1()
obj2 = Child2()

obj2.method()

obj2.method2()

Hybrid Inheritance
class Parent:
def method(self):
print("This is the parent class")

class Child1(Parent):
def method1(self):
print("This is child class 1")

class Child2(Parent):
def method2(self):
print("This is child class 2")

class GrandChild(Child1, Child2):


def method3(self):
print("This is the grandchild class")

obj = GrandChild()
obj.method()
obj.method1()
obj.method2()
obj.method3()
11.a) Explain the set data type with suitable example.
 A Set in Python programming is an unordered collection data type that is iterable and has no
duplicate elements.
 While sets are mutable, meaning you can add or remove elements after their creation, the
individual elements within the set must be immutable and cannot be changed directly.
 Set are represented by { } (values enclosed in curly braces)
 Sets are useful when you want to store non-redundant items or perform operations like union,
intersection, and difference on collections of data.
 EX:
numbers_list = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers_list)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}
b). Create a list in python and apply.
i. Slice operator.
ii. append()
iii. Pop() and
iv. len ().
# Step 1: Create a list
my_list = [1, 2, 3, 4, 5]

# Step 2: Use the slice operator to get a sublist


sliced_list = my_list[1:4] # This gives [2, 3, 4]

# Step 3: Append an element to the list


my_list.append(6) # Now, my_list is [1, 2, 3, 4, 5, 6]

# Step 4: Pop an element from the list


popped_element = my_list.pop() # Removes and returns the last element, which is 6
# Now, my_list is [1, 2, 3, 4, 5]

# Step 5: Get the length of the list


list_length = len(my_list) # This returns 5

After applying these operations, the list my_list contains [1, 2, 3, 4, 5] and the list_length variable holds
the value 5.
12. Write a python code to read a CSV file using pandas module and print the first and last five lines of
a file.
import pandas as pd

# Replace 'your_file.csv' with the path to your CSV file


file_path = 'your_file.csv'

# Read the CSV file into a DataFrame


df = pd.read_csv(file_path)

# Print the first five lines of the file


print("First five lines:")
print(df.head())

# Print the last five lines of the file


print("\nLast five lines:")
print(df.tail())

Replace 'your_file.csv' with the actual path to your CSV file. This code will read the file and display the
first and last five rows of the DataFrame.
13. a) What are looping statements? Explain with example.
 Looping statements are used to execute a block of code repeatedly based on a condition or a
sequence.
 Python supports two main types of loops:
1. for Loop
 The for loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or
other iterable objects.
 Example:
n=4
for i in range(0, n):
print(i)
2. while Loop
 A while loop executes as long as a condition is True.
 If the condition becomes False, the loop stops.
 Example:
count = 0
while (count < 3):
count = count + 1
print("Hello Divyanshu")
These are the basics of looping in Python with examples.
b) Write a Python program to calculate area of triangle
 Here is a Python program to calculate the area of a triangle using the Heron's formula and a
basic formula for right triangles.
def areaTriangle(a, b, c):
s = (a+b+c)/2
return (s*(s-a)*(s-b)*(s-c))**0.5

a=7
b=8
c=9
print('Area = {:.2f}'.format(areaTriangle(a, b, c)))
14) a) Explain any 4 functions in random module.
 The random module in Python provides functions to generate random numbers and make
random selections. Here are four commonly used functions:
1. random()
 Purpose: Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).
 Example:
import random
print(random.random()) # Output: e.g., 0.7531

2. randint(a, b)
 Purpose: Returns a random integer between a and b (both inclusive).
 Example:
print(random.randint(1, 10))
3. choice(seq)
 Purpose: Selects a random element from a non-empty sequence (like a list, tuple, or string).
 Example:
options = ['apple', 'banana', 'cherry']
print(random.choice(options))

4. shuffle(seq)
 Purpose: Randomly shuffles the elements of a mutable sequence (like a list) in place.
 Example:
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)

b) Explain the Command Line Arguments using getopt module.


Command Line Arguments
 The arguments that are given after the name of the program in the command line
shell of the operating system are known as Command Line Arguments.
 Python provides various ways of dealing with these types of arguments.
Using getopt module
 The getopt module in Python is used to parse command-line arguments passed to a
script.
 It provides functionality similar to the Unix getopt() function and allows developers
to specify short and long options for command-line arguments.
 Syntax: getopt.getopt(args, options, [long_options])
 Parameters:
 args: List of arguments to be passed.
 options: String of option letters that the script want to recognize. Options that
require an argument should be followed by a colon (:).
 long_options: List of string with the name of long options. Options that require
arguments should be followed by an equal sign (=).
 Return Type: Returns value consisting of two elements: the first is a list of
(option, value) pairs. The second is the list of program arguments left after the
option list was stripped.
15.a) What are the difference between del, remove(), and pop() method?

del remove() pop()

del is a keyword. It is a method. pop() is a method.

To delete value this method


To delete value it uses the This method also uses the
uses the value as a
index. index as a parameter to delete.
parameter.

The del keyword doesn’t return The remove() method


pop() returns deleted value.
any value. doesn’t return any value.

The del keyword can delete the


At a time it deletes only one At a time it deletes only one
single value from a list or delete
value from the list. value from the list.
the whole list at a time.

It throws index error in case of It throws value error in case It throws index error in case of
the index doesn’t exist in the of value doesn’t exist in the an index doesn’t exist in the
list. list. list.
b) Explain keys(), values() and items of Dictionary.
 In Python, a dictionary is a collection of key-value pairs.
 The methods keys(), values(), and items() are used to access the dictionary's components in
different ways.
1. keys() Method
 Purpose: Returns a view object containing all the keys in the dictionary.
 Type: The view object acts like a set, meaning it doesn't allow duplicate keys and supports set
operations.
 Usage:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.keys()) # Output: dict_keys(['a', 'b', 'c'])
2. values() Method
 Purpose: Returns a view object containing all the values in the dictionary.
 Type: The view object can contain duplicate values, unlike keys.
 Usage:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.values()) # Output: dict_values([1, 2, 3])
3. items() Method
 Purpose: Returns a view object containing all the key-value pairs in the dictionary as tuples.
 Type: Each element in the view object is a tuple (key, value).
 Usage:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.items())
16. a) How can a CSV file be created and manipulated in Python using CSV module ?
b) Explain the methods for Pickling and Unpickling.
Pickling
 Pickling is the process of converting a Python object into a byte stream (serialization).
 This byte stream can be written to a file or sent over a network.
Steps for Pickling:
1. Import the pickle module.
2. Open a file in binary write mode (wb).
3. Use pickle.dump() to serialize the object and write it to the file.
Example:
import pickle
# Define a Python object
person = {
"name": "Alice",
"age": 30,
"gender": "female"
}
# Pickle the object to a binary file
with open("person.pickle", "wb") as file:
pickle.dump(person, file)

print("Pickling completed")
Unpickling
 Unpickling is the process of converting a byte stream back into the original Python object
(deserialization).
Steps for Unpickling:
1. Import the pickle module.
2. Open the file containing the pickled data in binary read mode (rb).
3. Use pickle.load() to deserialize the byte stream into a Python object.
Example:
import pickle
# load the data from a file
with open('data.pkl', 'rb') as f:
data = pickle.load(f)
# print the data
print(data)
17.a) Explain seek() and tell() with an example.
 In Python, seek() and tell() are methods used with file objects to work with the file's current
position (file pointer).
1. seek(offset, whence):
 Moves the file pointer to a specified location in the file.
 Parameters:
o offset: Number of bytes to move the pointer.
o whence: The reference point from where the offset is applied.
 0 (default): Start of the file.
 1: Current file position.
 2: End of the file.
2. tell():
 Returns the current position of the file pointer (in bytes) from the start of the file.

Example:
# Open a file in read mode
with open("example.txt", "r") as file:
# Read the first 10 characters
content = file.read(10)
print("Content read:", content)

# Get the current file pointer position


position = file.tell()
print("Current position:", position)

# Move the file pointer to the beginning of the file


file.seek(0)
print("Position after seek to start:", file.tell())

# Move the file pointer 5 bytes forward from the current position
file.seek(5, 0)
print("Position after moving 5 bytes forward:", file.tell())

# Move the file pointer to the end of the file


file.seek(0, 2)
print("Position at the end of the file:", file.tell())
b) What is Polymorphism? What are the main advantages of Polymorphism?
Polymorphism
 The word polymorphism means having many forms.
 In programming, polymorphism means the same function name (but different signatures)
being used for different types.
 The key difference is the data types and number of arguments used in function.
Advantages:
 Reusable code: Developers can write code that can be used in multiple scenarios and with
different objects.
 Flexible code: Code can adapt to different situations and object types.
 Improved readability: Developers can write more concise and expressive code.
 Better error handling: Developers can write more robust error handling mechanisms.
 Simple debugging: Code is easier to debug.
 Multiple data types: A single variable can store multiple data types

18. a) Write a Python program to create a Bar Chart from CSV files using Matplotlib.

import pandas as pd

import matplotlib.pyplot as plt

def create_bar_chart(csv_file):

df = pd.read_csv(csv_file)

df.plot(kind='bar', x='Category', y='Value', legend=False, figsize=(10, 6))

plt.xlabel('Category')

plt.ylabel('Value')

plt.title('Bar Chart from CSV Data')

plt.show()

csv_file = 'data.csv'

create_bar_chart(csv_file)
b) What is JSON? Explain different JSON formats.
 JSON (JavaScript Object Notation) is widely used in Python for data interchange.
 Python too supports JSON with a built-in package called JSON.
 This package provides all the necessary tools for working with JSON Objects
JSON Formats in Python
1.json.dumps(): Converts a Python object into a JSON string.
2.json.loads(): Parses a JSON string and converts it into a Python object.
3.json.dump(): Writes a Python object to a file in JSON format.
4.json.load(): Reads a JSON file and converts it into a Python object.
EXAMPLE:
import json

# Python object (dict)


data = {
"name": "John Doe",
"age": 30,
"is_student": False,
"hobbies": ["reading", "swimming", "coding"],
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
}
}
# Convert Python object to JSON string
json_str = json.dumps(data, indent=4)

print("JSON String:")
print(json_str)

# Convert JSON string back to Python object


data_from_json = json.loads(json_str)

print("\nPython Object:")
print(data_from_json)
16. a) How can a CSV file be created and manipulated in Python using CSV module ?
 The csv module in Python makes it easy to work with CSV files, enabling you to read, write, and
manipulate data in a structured way.

Creating a CSV File


1. Use the csv.writer() function to write data into a CSV file.
2. Write rows with writer.writerow() or writer.writerows().
Reading and Manipulating a CSV File
1. Use csv.reader() to read data from a CSV file.
2. Process the rows and modify them as needed.
Example: Creating and Manipulating a CSV File
import csv
# Step 1: Create and write to a CSV file
filename = "example.csv"
# Data to write
data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "Los Angeles"],
["Charlie", 35, "Chicago"]
]
# Writing to the file
with open(filename, mode="w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(data)

print(f"{filename} created successfully!")

# Step 2: Read and manipulate the CSV file


with open(filename, mode="r", newline="", encoding="utf-8") as file:
reader = csv.reader(file)
rows = list(reader) # Read all rows into a list

# Manipulate the data: Add a new row


new_row = ["Diana", 28, "San Francisco"]
rows.append(new_row)

# Step 3: Write the manipulated data back to the file


with open(filename, mode="w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(rows)

print(f"{filename} updated successfully!")

# Step 4: Verify the updated file


with open(filename, mode="r", newline="", encoding="utf-8") as file:
reader = csv.reader(file)
for row in reader:
print(row)

You might also like