Python MP2
Python MP2
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).
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.
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.
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.
Types of conversions:
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
1. Sequential execution: Default flow where statements execute line by line from top to
bottom
4. Jump statements:
Conversion functions:
Utility functions:
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
Access modifiers control visibility and accessibility of class attributes and methods:
Important notes:
11. Write a Python Program to draw a multiline graph by reading data from
CSV files and using matplotlib.
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')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.title('Sales Data Visualization')
plt.legend()
plt.grid(True)
plt.show()
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
# Data to send
post_data = {
'title': 'My New Post',
'body': 'This is the content of my post',
'userId': 1
}
if response.status_code == 201:
created_post = response.json()
print(f"Post created with ID: {created_post['id']}")
headers = {
'User-Agent': 'MyApp/1.0',
'Accept': 'application/json'
}
params = {
'q': 'python',
'sort': 'stars',
'order': 'desc'
}
if response.status_code == 200:
data = response.json()
print(f"Found {data['total_count']} repositories")
# Execute examples
get_user_info()
create_post()
advanced_request()
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"
Default arguments:
(b) Explain the steps to reading and writing CSV files in Python. Reading CSV files:
15. (a) Explain the various operations that can be performed on Lists in
Python.
List operations:
(b) Discuss the built-in functions used on Dictionaries in Python. Dictionary built-in
functions:
16. (a) Discuss the steps to read and write binary files in Python.
17. (a) Explain the steps to create classes and objects in Python.
Creating classes:
Creating objects:
(b) Discuss the different types of files in Python. File types in Python:
18. (a) Explain rolling dice with Plotly. Write a program to illustrate the same.
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)]
fig.update_layout(
title='Dice Rolling Results',
xaxis_title='Dice Face',
yaxis_title='Frequency',
showlegend=False
)
fig.show()
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