0% found this document useful (0 votes)
2 views14 pages

Python MP2

The document contains a Python exam paper with solutions divided into three parts: Part A covers basic concepts and definitions, Part B discusses control flow statements and built-in functions, and Part C focuses on advanced topics like file handling and object-oriented programming. Each part consists of multiple questions with detailed explanations and code examples. The exam tests knowledge on Python programming fundamentals, libraries, and practical applications.

Uploaded by

rorip93554
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)
2 views14 pages

Python MP2

The document contains a Python exam paper with solutions divided into three parts: Part A covers basic concepts and definitions, Part B discusses control flow statements and built-in functions, and Part C focuses on advanced topics like file handling and object-oriented programming. Each part consists of multiple questions with detailed explanations and code examples. The exam tests knowledge on Python programming fundamentals, libraries, and practical applications.

Uploaded by

rorip93554
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/ 14

Python Exam Paper 2 - Solutions

PART - A (Answer any 4 questions, 2 marks each)


1. Why Python is called as Multi-Paradigm Programming Language?

Python supports multiple programming paradigms including procedural, object-oriented,


functional, and imperative programming. It allows developers to choose the most suitable
approach for their specific problem.

2. What is a keyword and literals in Python programming language? Give


examples.

Keywords: Reserved words with predefined meanings (if, else, for, while, def, class, import,
return). Literals: Fixed values in code representing data (42, "hello", 3.14, True, None).

3. Explain the concept of indexing and slicing in Lists.

Indexing: Accessing individual elements using position numbers (0-based). Example:


list[0] gets first element. Slicing: Extracting portions using list[start:end:step]
syntax. Example: list[1:4] gets elements from index 1 to 3.

4. How are dictionaries different from lists in Python?

Dictionaries use key-value pairs with unique keys for access, while lists use numerical
indices. Dictionaries are unordered (before Python 3.7) and optimized for lookups, lists are
ordered sequences.

5. Explain MRO in Multiple Inheritance.

MRO (Method Resolution Order) determines the order in which Python searches for methods
in multiple inheritance. It follows C3 linearization algorithm to avoid diamond problem and
ensure consistent method resolution.

6. What is the use of Matplotlib Library?

Matplotlib is a comprehensive plotting library for creating static, interactive, and animated
visualizations including line plots, bar charts, histograms, scatter plots, and complex multi-
panel figures.

PART - B (Answer any 4 questions, 5 marks each)


7. Explain the importance of type conversions in Python and how it can be
performed.

Importance of type conversions:


• Compatibility: Enables operations between different data types (string + number
requires conversion)
• User input handling: All user input is initially string, needs conversion for
calculations
• File operations: Data read from files is typically string format, requires conversion
for processing
• Mathematical operations: Ensures correct arithmetic operations without type errors
• Data validation: Convert and validate data before processing in applications

Types of conversions:

• Implicit conversion (automatic): Python automatically converts compatible types


o Example: 3 + 4.5 = 7.5 (int to float conversion)
o Smaller datatype converted to larger to prevent data loss
• Explicit conversion (manual): Using built-in conversion functions
o int(): converts to integer, float(): converts to floating point
o str(): converts to string, bool(): converts to boolean
o list(), tuple(), set(): converts to respective collection types

Practical examples:

python
# String to number conversion
age = int(input("Enter age: ")) # Convert string input to integer
price = float("25.99") # Convert string to float

# Number to string conversion


score = str(95) # Convert integer to string for
concatenation

8. Describe the various control flow statements in Python.

1. Sequential execution: Default flow where statements execute line by line from top to
bottom

2. Conditional statements (Decision making):

• if statement: Executes block only if condition is true


o Syntax: if condition: statements
• if-else statement: Executes one of two blocks based on condition
o Syntax: if condition: block1 else: block2
• if-elif-else statement: Handles multiple conditions in sequence
o Syntax: if cond1: block1 elif cond2: block2 else: block3
• Nested if: if statements inside other if statements for complex logic

3. Iterative statements (Loops):

• for loop: Iterates over sequences (lists, strings, ranges)


o Syntax: for variable in sequence: statements
o Used when number of iterations is known or finite
• while loop: Repeats while condition remains true
o Syntax: while condition: statements
o Used when number of iterations is unknown
• nested loops: Loops within loops for multi-dimensional processing

4. Jump statements:

• break: Exits current loop completely


• continue: Skips remaining statements in current iteration
• pass: Placeholder statement, does nothing

9. Discuss the built-in functions used on Tuples.

Information and measurement functions:

• len(tuple): Returns number of elements in tuple


• max(tuple): Finds maximum value (works with comparable elements)
• min(tuple): Finds minimum value (works with comparable elements)
• sum(tuple): Calculates sum of numeric elements in tuple
• any(tuple): Returns True if any element is true
• all(tuple): Returns True if all elements are true

Search and count functions:

• count(value): Counts occurrences of specific element in tuple


• index(value): Returns index of first occurrence of specified element
• index(value, start, end): Searches within specified range

Conversion functions:

• tuple(iterable): Converts other iterables (list, string, set) to tuple


• list(tuple): Converts tuple to list for modification purposes
• set(tuple): Converts tuple to set (removes duplicates)

Utility functions:

• sorted(tuple): Returns new sorted list from tuple elements


• reversed(tuple): Returns iterator for reverse iteration
• enumerate(tuple): Returns iterator with index-value pairs

Example usage:

python
numbers = (1, 2, 3, 2, 4, 2)
print(len(numbers)) # Output: 6
print(numbers.count(2)) # Output: 3
print(numbers.index(3)) # Output: 2

10. Explain the concept of access modifiers in Python.

Access modifiers control visibility and accessibility of class attributes and methods:

1. Public access (no prefix):

• Default accessibility level in Python


• Accessible from anywhere (inside class, outside class, subclasses)
• Syntax: self.attribute or def method(self):
• Example: self.name = "John" - can be accessed as obj.name

2. Protected access (single underscore prefix):

• Intended for internal use within class and its subclasses


• Python convention, not strictly enforced
• Syntax: self._attribute or def _method(self):
• Still accessible from outside but indicates "internal use"
• Example: self._id = 123 - should be accessed only within class hierarchy

3. Private access (double underscore prefix):

• Restricted access through name mangling mechanism


• Python changes attribute name to _ClassName__attribute
• Syntax: self.__attribute or def __method(self):
• Cannot be directly accessed outside class
• Example: self.__password becomes _User__password internally

Important notes:

• Python uses naming conventions rather than strict enforcement


• Private attributes are still accessible via name mangling
• Access modifiers provide code organization and prevent accidental modifications

11. Write a Python Program to draw a multiline graph by reading data from
CSV files and using matplotlib.

Program explanation and approach:

• Read CSV data containing multiple columns for different lines


• Extract x-axis data and multiple y-axis datasets
• Create multiple line plots on same graph with different styling
• Add proper labels, legend, and formatting for clarity

python
import matplotlib.pyplot as plt
import pandas as pd
# Method 1: Using pandas (recommended for CSV handling)
def create_multiline_graph_pandas():
# Read CSV file with headers
data = pd.read_csv('sales_data.csv')

# Create figure with custom size


plt.figure(figsize=(12, 8))

# Plot multiple lines with different styles


plt.plot(data['Month'], data['Product_A'], label='Product A',
marker='o', linewidth=2, color='blue')
plt.plot(data['Month'], data['Product_B'], label='Product B',
marker='s', linewidth=2, color='red')
plt.plot(data['Month'], data['Product_C'], label='Product C',
marker='^', linewidth=2, color='green')

# Customize the graph


plt.xlabel('Month', fontsize=12)
plt.ylabel('Sales (in thousands)', fontsize=12)
plt.title('Monthly Sales Comparison - Multiple Products', fontsize=14,
fontweight='bold')
plt.legend(loc='upper left')
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)

# Adjust layout and display


plt.tight_layout()
plt.show()

# Method 2: Using csv module


import csv
def create_multiline_graph_csv():
months, product_a, product_b, product_c = [], [], [], []

# Read CSV file manually


with open('sales_data.csv', 'r') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
months.append(row['Month'])
product_a.append(float(row['Product_A']))
product_b.append(float(row['Product_B']))
product_c.append(float(row['Product_C']))

# Create multiline plot


plt.figure(figsize=(10, 6))
plt.plot(months, product_a, 'o-', label='Product A')
plt.plot(months, product_b, 's-', label='Product B')
plt.plot(months, product_c, '^-', label='Product C')

plt.xlabel('Month')
plt.ylabel('Sales')
plt.title('Sales Data Visualization')
plt.legend()
plt.grid(True)
plt.show()

# Execute the function


create_multiline_graph_pandas()

12. Explain requests library with an example.

Requests library overview:

• Purpose: Simplified HTTP library for making web requests in Python


• Installation: pip install requests
• Key features: User-friendly API, automatic JSON decoding, session management,
authentication support

Main HTTP methods supported:

• GET: Retrieve data from server


• POST: Send data to server (form submissions, API calls)
• PUT: Update existing resources
• DELETE: Remove resources from server
• PATCH: Partial updates to resources

Key functionalities:
• Response handling: Access status codes, headers, content, JSON data
• Request customization: Headers, parameters, authentication, timeout settings
• Session management: Persist cookies and settings across requests
• Error handling: Built-in exception handling for connection issues

Comprehensive example:

python
import requests
import json

# GET request example - fetching user data


def get_user_info():
url = "https://jsonplaceholder.typicode.com/users/1"

# Make GET request with timeout


response = requests.get(url, timeout=5)

# Check if request was successful


if response.status_code == 200:
user_data = response.json()
print(f"User Name: {user_data['name']}")
print(f"Email: {user_data['email']}")
else:
print(f"Error: {response.status_code}")

# POST request example - sending data


def create_post():
url = "https://jsonplaceholder.typicode.com/posts"

# Data to send
post_data = {
'title': 'My New Post',
'body': 'This is the content of my post',
'userId': 1
}

# Send POST request with JSON data


response = requests.post(url, json=post_data)

if response.status_code == 201:
created_post = response.json()
print(f"Post created with ID: {created_post['id']}")

# Request with custom headers and parameters


def advanced_request():
url = "https://api.github.com/search/repositories"

headers = {
'User-Agent': 'MyApp/1.0',
'Accept': 'application/json'
}

params = {
'q': 'python',
'sort': 'stars',
'order': 'desc'
}

response = requests.get(url, headers=headers, params=params)

if response.status_code == 200:
data = response.json()
print(f"Found {data['total_count']} repositories")

# Execute examples
get_user_info()
create_post()
advanced_request()

PART - C (Answer any 4 questions, 8 marks each)


13. (a) Explain string slicing with examples.

String slicing syntax: string[start:end:step]


• start: Beginning index (inclusive)
• end: Ending index (exclusive)
• step: Step size (default 1)

Examples:

python
text = "Hello World"
print(text[0:5]) # "Hello"
print(text[6:]) # "World"
print(text[:5]) # "Hello"
print(text[::2]) # "HloWrd"
print(text[::-1]) # "dlroW olleH" (reverse)
print(text[1:8:2]) # "el o"

(b) Explain Command Line Arguments Command line arguments:

• Values passed to program when executed from command line


• Accessed through sys.argv list
• sys.argv[0] contains script name
• Additional arguments stored in sys.argv[1:]
• argparse module provides advanced argument parsing
• Enables program customization without code modification
• Useful for batch processing and automation scripts

14. (a) Explain default arguments and variable length arguments.

Default arguments:

• Parameters with predefined values in function definition


• Used when argument not provided during function call
• Must appear after non-default parameters
• Syntax: def func(param1, param2=default_value):

Variable length arguments:

• *args: Accepts variable number of positional arguments as tuple


• **kwargs: Accepts variable number of keyword arguments as dictionary
• Enables flexible function definitions
• Example: def func(*args, **kwargs):

(b) Explain the steps to reading and writing CSV files in Python. Reading CSV files:

• Import csv module: import csv


• Open file in read mode: with open('file.csv', 'r') as file:
• Create reader object: reader = csv.reader(file)
• Iterate through rows: for row in reader:
• Use DictReader for column names: csv.DictReader(file)

Writing CSV files:

• Open file in write mode: with open('file.csv', 'w') as file:


• Create writer object: writer = csv.writer(file)
• Write rows: writer.writerow(['col1', 'col2'])
• Use DictWriter for dictionary data: csv.DictWriter(file, fieldnames)

15. (a) Explain the various operations that can be performed on Lists in
Python.

List operations:

• Access: list[index], list[start:end]


• Modification: list[index] = value
• Addition: append(), insert(), extend(), + operator
• Removal: remove(), pop(), del, clear()
• Searching: index(), count(), in operator
• Sorting: sort(), reverse(), sorted()
• Copying: copy(), list(), slicing
• Iteration: for loops, list comprehensions

(b) Discuss the built-in functions used on Dictionaries in Python. Dictionary built-in
functions:

• Access: get(), keys(), values(), items()


• Modification: update(), setdefault(), pop(), popitem()
• Information: len(), bool(), str(), repr()
• Copying: copy(), dict()
• Clearing: clear()
• Membership: in operator (checks keys)
• Creation: fromkeys() class method
• Iteration: Direct iteration over keys, values, or items

16. (a) Discuss the steps to read and write binary files in Python.

Reading binary files:

• Open file in binary read mode: with open('file.bin', 'rb') as f:


• Read entire file: data = f.read()
• Read specific bytes: data = f.read(10)
• Process binary data as bytes object
• Use struct module for structured binary data

Writing binary files:

• Open file in binary write mode: with open('file.bin', 'wb') as f:


• Write bytes object: f.write(b'binary data')
• Use struct.pack() for structured data
• Convert strings to bytes: string.encode()
• Handle endianness for cross-platform compatibility

(b) How polymorphism is achieved in Object Oriented Programming? Polymorphism


achievement methods:

• Method overriding: Child class redefines parent class methods


• Duck typing: Objects treated based on behavior, not inheritance
• Operator overloading: Redefining operators for custom classes
• Method overloading: Multiple methods with same name (using default parameters)
• Abstract base classes: Define common interface for related classes
• Interface implementation: Multiple classes implementing same interface
• Runtime method resolution: Python determines method to call at runtime

17. (a) Explain the steps to create classes and objects in Python.

Creating classes:

• Use class keyword: class ClassName:


• Define attributes and methods within class body
• Use __init__() method for initialization
• Define instance methods with self parameter
• Create class variables for shared data

Creating objects:

• Instantiate class: object_name = ClassName()


• Pass arguments to constructor if required
• Access attributes: object_name.attribute
• Call methods: object_name.method()
• Multiple objects can be created from same class

(b) Discuss the different types of files in Python. File types in Python:

• Text files: Human-readable, character-based (.txt, .csv, .json)


• Binary files: Machine-readable, byte-based (.exe, .jpg, .mp3)
• CSV files: Comma-separated values for tabular data
• JSON files: JavaScript Object Notation for structured data
• XML files: Extensible Markup Language for hierarchical data
• Pickle files: Python-specific serialization format
• Configuration files: .ini, .cfg for application settings
• Log files: Application event recording

18. (a) Explain rolling dice with Plotly. Write a program to illustrate the same.

Rolling dice visualization: Rolling dice simulation shows probability distribution of


outcomes. Plotly creates interactive histograms showing frequency of each face value.

python
import plotly.graph_objects as go
import random

def roll_dice(num_rolls):
"""Simulate rolling a dice num_rolls times"""
results = []
for _ in range(num_rolls):
results.append(random.randint(1, 6))
return results

def plot_dice_results(results):
"""Plot dice rolling results using Plotly"""
# Count frequency of each face
counts = [results.count(i) for i in range(1, 7)]

# Create bar chart


fig = go.Figure(data=go.Bar(
x=list(range(1, 7)),
y=counts,
text=counts,
textposition='auto'
))

fig.update_layout(
title='Dice Rolling Results',
xaxis_title='Dice Face',
yaxis_title='Frequency',
showlegend=False
)

fig.show()

# Simulate rolling dice 1000 times


dice_results = roll_dice(1000)
plot_dice_results(dice_results)
(b) Write a program to read data from GitHub and use the data to visualize using
plotly.

python
import requests
import plotly.graph_objects as go
import plotly.express as px

def get_github_data(username):
"""Fetch GitHub user repositories data"""
url = f"https://api.github.com/users/{username}/repos"
response = requests.get(url)

if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
return None

def visualize_github_data(repos_data):
"""Create visualizations from GitHub data"""
if not repos_data:
return

# Extract languages and stars


languages = {}
stars = []
names = []

for repo in repos_data:


if repo['language']:
languages[repo['language']] = languages.get(repo['language'],
0) + 1
stars.append(repo['stargazers_count'])
names.append(repo['name'])

# Create language distribution pie chart


fig1 = go.Figure(data=go.Pie(
labels=list(languages.keys()),
values=list(languages.values()),
title="Programming Languages Distribution"
))
fig1.show()

# Create stars bar chart


fig2 = go.Figure(data=go.Bar(
x=names[:10], # Top 10 repos
y=stars[:10],
title="Repository Stars"
))
fig2.update_layout(xaxis_tickangle=-45)
fig2.show()

# Fetch and visualize data


username = "octocat" # Replace with desired username
repos = get_github_data(username)
visualize_github_data(repos)

You might also like