0% found this document useful (0 votes)
6 views7 pages

Solved Python Sem 3

The document provides an overview of Python programming concepts, including identifiers, membership operators, string functions, tuples, modules, and dictionary operations. It also explains function categories, string slicing, data frames, file opening modes, and data cleaning techniques using pandas. Additionally, it includes examples of using lambda, map, filter, and reduce functions, along with groupby operations and data visualization using matplotlib.
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)
6 views7 pages

Solved Python Sem 3

The document provides an overview of Python programming concepts, including identifiers, membership operators, string functions, tuples, modules, and dictionary operations. It also explains function categories, string slicing, data frames, file opening modes, and data cleaning techniques using pandas. Additionally, it includes examples of using lambda, map, filter, and reduce functions, along with groupby operations and data visualization using matplotlib.
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

[Link] ANSWER (1,2,3).

1. What are identifiers? Write rules for Characteristics:


naming identifiers. • Immutable (cannot be changed).
Identifiers are names given to • Allows duplicate values &
variables, functions, classes, etc., in maintains order.
Python. 5. Explain any two dictionary
Rules: i. Must start with a letter or methods.
underscore (_). • keys() → returns all keys
ii. Cannot start with a digit. • [Link]()
iii. Can contain letters, digits, and • get() → returns value of a key (no
underscore. error if key missing)
iv. Case-sensitive (Age ≠ age). [Link]("name")
v. Cannot use keywords (like if, while, 6. What is a module? Give examples
etc.). of built-in modules.
A module is a Python file containing
2. Explain membership operators with functions, classes, or variables that can
examples. be reused.
Membership operators test whether a Examples: math, random, datetime, os.
value is present in a sequence.
• in → True if value exists 7. Write Python code to open a file in
• 3 in [1,2,3] # True write mode and write a line into it.
• not in → True if value does not f = open("[Link]", "w")
exist [Link]("Hello Python")
"a" not in "cat" # False [Link]()

3. Give any four basic string functions [Link] ANSWER


with examples. 1. Explain different types of function
• len() – returns length categories in Python.
• len("hello") # 5 In Python, functions are divided into the
• upper() – converts to uppercase following categories:
• "hi".upper() # 'HI' (1) Built-in Functions
• lower() – converts to lowercase These functions are already defined in
• "HI".lower() # 'hi' Python and can be used directly without
• replace() – replaces substring any declaration.
"hello".replace("h","H") # 'Hello' Examples:
• print() – displays output
4. What is a tuple? Write two • len() – returns length
characteristics of tuples. • type() – gives data type
A tuple is an ordered collection of (2) User-Defined Functions
elements enclosed in parentheses, e.g.,

1
These are functions created by the • step → jump (optional)
programmer using the def keyword. Examples:
Example: 1. Basic slicing
def add(a, b): s = "PYTHON"
return a + b print(s[0:3]) # Output: PYT
(3) Functions with Arguments and 2. Omitting start or end
Return Values s = "PYTHON"
Functions may take arguments and may print(s[:4]) # PYTH
or may not return values. print(s[2:]) # THON
Examples: 3. Negative indexes
• With arguments, with return s = "PYTHON"
value print(s[-4:-1]) # THO
• def square(x): 4. Using step value
• return x*x s = "PYTHON"
• With arguments, no return print(s[0:6:2]) # PTO
value String slicing helps in extracting
• def show(name): substrings, reversing strings, and
• print(name) manipulating text.
(4) Lambda (Anonymous) Functions
These are small, one-line functions 3. Write a Python program to
written using the lambda keyword. demonstrate set operations (union,
Example: intersection, difference).
square = lambda x: x*x Program:
(5) Recursion Functions # Demonstrating set operations
Functions that call themselves A = {1, 2, 3, 4}
repeatedly to solve a problem. B = {3, 4, 5, 6}
Example:
def fact(n): # Union
if n==0: return 1 print("Union:", A | B)
return n * fact(n-1)
# Intersection
2. Explain string slicing with suitable print("Intersection:", A & B)
examples.
String slicing is the process of # Difference
extracting a part (substring) from a print("Difference A-B:", A - B)
string using the slice operator print("Difference B-A:", B - A)
[start:end:step]. Output:
Syntax: Union: {1, 2, 3, 4, 5, 6}
string[start : end : step] Intersection: {3, 4}
• start → starting index (inclusive) Difference A-B: {1, 2}
• end → ending index (exclusive) Difference B-A: {5, 6}

2
This program displays all major set f = open("[Link]", "r") # open file in
operations. read mode
data = [Link]() # read entire file
4. Explain the steps to create and print("File contents:\n", data)
import a user-defined module. [Link]()
A module is a Python file that contains Explanation:
functions, variables, and classes which • open("[Link]", "r") → opens
can be reused. file in read mode
Steps to Create and Use a User- • read() → reads full content as a
Defined Module: string
Step 1: Create a module file • print() → displays the text
Create a Python file, e.g., [Link] • close() → closes the file after
def add(x, y): using
return x + y
[Link] ANSWE
def greet(): 1. Explain lambda, map, filter and
print("Hello from module!") reduce functions with examples. (4
Step 2: Save the file marks)
Save [Link] in the same folder as Lambda Function
your main program. A lambda function is an anonymous,
Step 3: Import the module in another single-line function defined using the
program lambda keyword.
Use any of the following methods: Syntax: lambda arguments : expression
Method 1: import module Example:
import mymodule square = lambda x: x*x
print([Link](5, 3)) print(square(5)) # 25
[Link]()
Method 2: from module import map() Function
function map() applies a function to every
from mymodule import add element of an iterable (list, tuple, etc.)
print(add(10, 20)) and returns a new map object.
Step 4: Run the main program Example:
The functions of the module are nums = [1, 2, 3, 4]
executed and reusable in any program. result = list(map(lambda x: x*2, nums))
print(result) # [2, 4, 6, 8]
5. Write a program to read the
contents of a file and display it. filter() Function
Program: filter() filters elements from an iterable
# Program to read and display file based on a condition (returns
contents True/False).
Example:

3
nums = [1, 2, 3, 4, 5, 6] • [Link]('age')
even = list(filter(lambda x: x%2==0, • clear(): removes all elements
nums)) • [Link]()
print(even) # [2, 4, 6]
4. Iterating Through Dictionary
reduce() Function You can iterate through keys, values, or
reduce() applies a function cumulatively both.
to elements of an iterable to reduce it to for key in d:
a single value. print(key, d[key])
It is available in functools module. OR
Example: for k, v in [Link]():
from functools import reduce print(k, v)
nums = [1, 2, 3, 4] These operations allow full control over
total = reduce(lambda a,b: a+b, nums) dictionary manipulation.
print(total) # 10
3. Write a detailed note on DataFrame
2. Explain dictionary operations: creation (using list, dictionary, and
adding, updating, deleting values and CSV file). (4 marks)
iterating. (4 marks) A DataFrame is a 2-dimensional, table-
Let d = {'name':'Rahul', 'age':20} like data structure provided by the
pandas library. It consists of rows and
1. Adding Elements columns similar to an Excel sheet or
You can add a new key–value pair by SQL table.
assignment. DataFrames can be created in multiple
d['city'] = 'Pune' ways:
Dictionary becomes: {'name':'Rahul',
'age':20, 'city':'Pune'} 1. Creating DataFrame from a List
Lists (list of values or list of lists) can be
2. Updating Values converted to a DataFrame.
Assigning a value to an existing key Example:
updates it. import pandas as pd
d['age'] = 21
OR use update() method: data = [[1, 'A'], [2, 'B'], [3, 'C']]
[Link]({'name':'Rohan'}) df = [Link](data, columns=['ID',
'Name'])
3. Deleting Elements print(df)
Multiple methods exist: Output:
• del statement ID Name
• del d['city'] 0 1 A
• pop(): removes the key and 1 2 B
returns its value 2 3 C

4
filtering, merging, grouping, and
2. Creating DataFrame from a exporting data.
Dictionary
Dictionary keys become column names Q4. LONG ANSWER
and values become column data. 1. Explain different file opening modes
Example: with examples. (4 marks)
import pandas as pd Python’s open() function is used to open a
file.
data = { Syntax:
'ID': [1, 2, 3], open(filename, mode)
'Name': ['A', 'B', 'C'], Common file opening modes:
'Marks': [85, 90, 95] 1. "r" – Read Mode
} Opens file for reading (default). File must
df = [Link](data) already exist.
print(df) Example:
Output: f = open("[Link]", "r")
ID Name Marks content = [Link]()
0 1 A 85
1 2 B 90 2. "w" – Write Mode
2 3 C 95 Creates a new file or overwrites an
existing one.
3. Creating DataFrame from a CSV File Example:
You can load CSV data using read_csv(). f = open("[Link]", "w")
Example: [Link]("Hello")
import pandas as pd
3. "a" – Append Mode
df = pd.read_csv("[Link]") Adds new data at the end of the file
print(df) without deleting existing content.
Explanation: Example:
• read_csv() automatically reads a f = open("[Link]", "a")
CSV file [Link]("New entry\n")
• First row becomes column
headings 4. "r+" – Read and Write Mode
• Data loads into a structured Allows both reading and writing. File must
DataFrame exist.
Example:
Conclusion: f = open("[Link]", "r+")
DataFrames are powerful structures in [Link]("Update")
pandas used extensively in data
analysis. They support easy indexing, 5. "w+" – Write and Read Mode

5
Creates file if not exist and allows both (c) Forward/Backward Fill
reading and writing. Overwrites content. df3 = [Link](method="ffill")
Example: df4 = [Link](method="bfill")
f = open("[Link]", "w+")
[Link]("Data") 2. Removing Duplicates
Duplicate rows create inconsistencies and
6. "b" – Binary Mode must be removed.
Used for images, audio, videos. Using duplicated()
Example: Identifies duplicate rows.
f = open("[Link]", "rb") [Link]()
Using drop_duplicates()
7. "t" – Text Mode (default) Removes duplicate rows.
Used for text files. clean_df = df.drop_duplicates()
f = open("[Link]", "rt") Data cleaning ensures that datasets are
These modes allow complete control over ready for analysis with correct and
how files are opened and modified. consistent values.

2. What is data cleaning? Explain Q5. LONG ANSWER


handling missing values and removing A. Explain groupby() in pandas. Write a
duplicates using pandas. (4 marks) Python program for grouping and
Data Cleaning aggregating data. (4 marks)
Data cleaning is the process of detecting groupby() in pandas
and correcting inaccurate, incomplete, or groupby() is used to split data into groups
inconsistent data. It is an essential step in based on one or more columns.
data preprocessing to improve data It helps in performing operations like sum,
quality. count, mean, max, etc., on groups of data.
Working of groupby():
1. Handling Missing Values • Split → divide data based on
Missing values appear as NaN in pandas. column
Common techniques: • Apply → apply aggregate function
(a) Using dropna() • Combine → return result as a
Removes rows or columns that contain DataFrame
missing values.
import pandas as pd Example Program:
df = pd.read_csv("[Link]") import pandas as pd
df1 = [Link]() # remove rows
with NaN data = {
(b) Using fillna() 'Department': ['IT', 'IT', 'HR', 'HR',
Replaces missing values with a specified 'Sales'],
value. 'Salary': [50000, 60000, 45000, 48000,
df2 = [Link](0) # replace NaN with 0 55000]

6
}
[Link](items, values)
df = [Link](data) [Link]("Product Sales")
[Link]("Products")
# Grouping and Aggregation [Link]("Sales")
result = [Link]()
[Link]('Department')['Salary'].mean()
OR Histogram
print(result) import [Link] as plt
Output:
Department data = [10,20,20,30,40,40,50,60,60,70]
HR 46500
IT 55000 [Link](data)
Sales 55000 [Link]("Distribution")
Name: Salary, dtype: int64 [Link]("Values")
Explanation: [Link]("Frequency")
• Data is grouped by Department [Link]()
• Mean salary is calculated for each
group

OR
B. Write a program to plot ANY ONE chart
using matplotlib (line / bar / histogram).
(4 marks)
Example: Line Chart
import [Link] as plt

x = [1, 2, 3, 4, 5]
y = [10, 14, 12, 18, 20]

[Link](x, y) # line chart


[Link]("Sales Growth")
[Link]("Month")
[Link]("Sales")
[Link]()

OR Bar Chart
import [Link] as plt

items = ["A", "B", "C"]


values = [30, 45, 20]

You might also like