Python Pyq
Python Pyq
Solve 1 (a)
Key Roles:
Allows label-based indexing (by column names) and position-based indexing (by
row/column indices).
Enables import/export of data from various file formats like CSV, Excel, SQL, JSON, etc.
1/49
How DataFrames Can Be Merged:
DataFrames can be merged using the merge() function in Pandas, which works similarly to
SQL joins.
Syntax:
python
Inner Join ( how='inner' ): Returns only the rows with matching keys in both
DataFrames.
Outer Join ( how='outer' ): Returns all rows from both DataFrames, with NaN where no
match is found.
Left Join ( how='left' ): All rows from the left DataFrame and matching rows from the
right.
Right Join ( how='right' ): All rows from the right DataFrame and matching rows from
the left.
Example:
python
import pandas as pd
Output:
nginx
ID Name Score
0 1 Alice 85
2/49
1 2 Bob 90
Let me know if you’d like the answers to the remaining parts of Q1 too.
1(d)
Q1 (d): Write a short note on different methods to read data from a file in Python.
Python provides several ways to read data from a file. Here are the most common methods:
python
2. Using readline()
Reads one line at a time from the file.
python
3/49
3. Using readlines()
Reads all lines and returns them as a list of strings.
python
python
python
import pandas as pd
df = pd.read_csv("data.csv")
print(df.head())
python
4/49
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
Summary:
Method Use Case
Let me know if you want explanations for 1(e) or any other part.
2(b)
Q2 (b): Explain the different numeric, assignment, and augmented assignment operators
used in Python.
[3 Marks]
5/49
Operator Description Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
// Floor Division 5 // 2 2
% Modulus 5 % 2 1
** Exponentiation 2 ** 3 8
2. Assignment Operator:
Used to assign a value to a variable.
= Assigns x = 10
+= x = x + y x += 3 Adds 3 to x
-= x = x - y x -= 2 Subtracts 2 from x
*= x = x * y x *= 2 Multiplies x by 2
/= x = x / y x /= 2 Divides x by 2
6/49
Operator Equivalent To Example Result
%= x = x % y x %= 2 Modulus
Example in Code:
python
x = 10
x += 5 # x becomes 15
x *= 2 # x becomes 30
Let me know if you’d like help with 2(c) or any other question.
2(c)
result = 10 + 5 * 2
First: 5 * 2 → 10
Then: 10 + 10 → 20
So, result = 20
result = (10 + 5) * 2
First: 10 + 5 → 15
Then: 15 * 2 → 30
So, result = 30
Highest () Parentheses
** Exponentiation
+, - Addition, subtraction
8/49
Precedence Operators Description
^ Bitwise XOR
` `
✅ Key Tip:
Use parentheses to make your expressions clear and avoid mistakes due to precedence
rules.
✅ Mini Example:
python
a = 5 + 2 * 3 ** 2
# 3 ** 2 = 9
# 2 * 9 = 18
# 5 + 18 = 23
So, a = 23
Let me know if you’d like help with Q2(a) or the next question.
3(a)
9/49
Q3 (a): What are the commonly used operators in Python? Explain operator overloading
with the help of an example.
[6 Marks]
10/49
class Book:
def __init__(self, pages):
self.pages = pages
b1 = Book(150)
b2 = Book(200)
Output:
yaml
5(a)
Q5 (a): What are functions in Python? Differentiate between built-in and user-defined
functions with suitable examples.
11/49
[5 Marks]
Functions are defined using the def keyword and can take parameters and return values.
2. User-defined Functions
🔹 1. Built-in Functions:
These are predefined functions provided by Python. You can use them directly without
defining them.
Examples:
python
🔹 2. User-defined Functions:
Functions created by the user using the def keyword.
Example:
12/49
python
def greet(name):
print("Hello,", name)
✅ Comparison Table:
Feature Built-in Functions User-defined Functions
✅ Conclusion:
Functions help make code organized and reusable.
Python provides many built-in functions, and we can also create user-defined functions
for custom logic.
Here's a clear and concise explanation of the following Python string methods:
13/49
✅ 1. find()
Definition:
Searches for a substring within a string and returns the lowest index where it is found.
Returns -1 if not found.
Example:
python
✅ 2. isalnum()
Definition:
Returns True if all characters in the string are alphanumeric (i.e., letters or numbers), and
False otherwise.
Example:
python
✅ 3. zfill()
Definition:
Pads the string with zeros ( 0 ) on the left until it reaches the specified length.
Syntax: string.zfill(width)
Example:
python
14/49
print("42".zfill(5)) # Output: '00042'
print("-42".zfill(5)) # Output: '-0042'
✅ 4. strip()
Definition:
Removes leading and trailing whitespaces (or specified characters) from the string.
Syntax: string.strip([chars])
Example:
python
✅ 5. split()
Definition:
Splits the string into a list of substrings based on a delimiter (default is whitespace).
Example:
python
data = "a,b,c"
print(data.split(',')) # Output: ['a', 'b', 'c']
✅ 6. rindex()
15/49
Definition:
Returns the highest index (last occurrence) of a substring. Raises a ValueError if the
substring is not found.
Example:
python
text = "banana"
print(text.rindex("a")) # Output: 5
# print(text.rindex("x")) # Raises ValueError
✅ Function Requirements:
Input: List X
Task:
✅ Python Code:
16/49
python
def Reverse(X):
for i in range(len(X) - 1, -1, -1):
print(X[i] * 2)
# Example usage:
X = [1, 3, 5, 7]
Reverse(X)
✅ Output:
14
10
6
2
This prints:
7×2 = 14
5×2 = 10
3×2 = 6
1×2 = 2
Let me know if you'd like to modify it to return a new list instead of printing!
reverse function
Here’s a more flexible version of the Reverse() function that returns the reversed list with
each element doubled, instead of just printing them:
17/49
✅ Revised Reverse() Function (Returns List)
python
def Reverse(X):
reversed_list = []
for i in range(len(X) - 1, -1, -1):
reversed_list.append(X[i] * 2)
return reversed_list
# Example usage:
X = [2, 4, 6, 8]
result = Reverse(X)
print("Reversed and Doubled List:", result)
✅ Output:
less
def Reverse(X):
return [x * 2 for x in reversed(X)]
Let me know if you want it to modify the original list, print each value line by line, or
anything else!
18/49
✅ Python's Default reverse() Function:
Python provides a built-in list method called reverse() which reverses a list in place
(modifies the original list). It does not return a new list.
🔹 Syntax:
python
list.reverse()
🔹 Example:
python
Output:
csharp
⚠️ Important Notes:
reverse() changes the original list.
It returns None .
python
X = [1, 2, 3, 4]
Y = X[::-1]
print(Y) # Output: [4, 3, 2, 1]
python
X = [1, 2, 3, 4]
Y = list(reversed(X))
print(Y) # Output: [4, 3, 2, 1]
Let me know if you'd like to use this with doubling elements too!
Sure! Here's how you can use the default reverse() method to solve the problem:
✅ "Write a program to display the elements in reverse order such that each displayed
element is twice of the original element of the list X."
python
def Reverse(X):
X.reverse() # Reverses the list in-place
for element in X:
print(element * 2)
20/49
# Example usage
X = [2, 4, 6, 8]
Reverse(X)
✅ Output:
16
12
8
4
Let me know if you want to keep the original list unchanged or store the result in another
list instead of printing!
Here’s how you can write the function mul() that takes a list L and separates its elements
into two lists: even_L and odd_L based on whether they're even or odd.
python
21/49
even_L.append(item)
else:
odd_L.append(item)
✅ Example Usage:
python
✅ Output:
less
Let me know if you want a version that returns the two lists instead of modifying them in-
place.
22/49
Opens the file,
✅ Python Program:
python
try:
# Open and read the file
with open(filename, 'r') as file:
content = file.read()
23/49
except FileNotFoundError:
print("Error: File not found.")
✅ Sample Output:
bash
Let me know if you want to count a specific character only, or make it case-insensitive.
24/49
Exchange data between programs or users
Logging errors
Mode Description
✅ Example:
25/49
python
List files/folders
This is done using Python's built-in os and os.path modules (or pathlib in newer code).
python
import os
26/49
✅ Example:
Assume a directory structure:
my_data/
├── file1.txt
├── file2.txt
└── subdir/
└── file3.txt
Code:
python
import os
✅ Output:
less
27/49
✅ Summary of os.walk() :
Element Description
Let me know if you want to perform actions like file filtering, searching, or copying during
traversal.
try:
# Step 2: Read contents from both files
with open(file1, 'r') as f1, open(file2, 'r') as f2:
28/49
content1 = f1.read()
content2 = f2.read()
except FileNotFoundError:
print("One of the input files was not found.")
✅ Example:
file1.txt
nginx
hello world
file2.txt
nginx
python programming
merged.txt
nginx
HELLO WORLD
PYTHON PROGRAMMING
29/49
Let me know if you want to preserve line breaks, ignore blank lines, or add file existence
checks before merging!
Sample list: [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
Expected Output: [(10, 20, 100), (40, 50, 100), (70, 80, 100)]
Here’s a Python program to replace the last value of each tuple in a list with a fixed value
(e.g., 100 ):
✅ Python Program
python
# Sample list
sample_list = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
✅ Output:
less
Modified List: [(10, 20, 100), (40, 50, 100), (70, 80, 100)]
30/49
✅ Explanation:
t[:-1] takes all elements except the last from tuple t .
+ joins them to form a new tuple with the last value replaced.
Let me know if you want to take the replacement value as user input!
Here's how to create a 5 × 2 integer NumPy array from the range 100 to 200, with a
difference of 10 between elements:
import numpy as np
✅ Output:
less
5x2 Array:
[[100 110]
31/49
[120 130]
[140 150]
[160 170]
[180 190]]
✅ Explanation:
np.arange(100, 200, 10) → generates numbers: 100, 110, ..., 190
Let me know if you'd like a version without NumPy (using pure Python).
✅ Syntax:
python
32/49
# Lambda to add 10 to a number
add10 = lambda x: x + 10
print(add10(5)) # Output: 15
python
def add10(x):
return x + 10
python
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # Output: [2, 4, 6, 8]
python
33/49
# Filter even numbers
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4, 6]
✅ Summary:
Feature Lambda Function
Let me know if you want lambda used in sorting, data structures, or GUI examples.
Here’s a simple Python program to calculate the GCD (Greatest Common Divisor) of two
numbers using both:
python
import math
34/49
# Calculate GCD
gcd = math.gcd(a, b)
# Output result
print("GCD is:", gcd)
# Call function
print("GCD is:", compute_gcd(a, b))
🧠 Example Input/Output:
yaml
Let me know if you also want to compute LCM or GCD of more than 2 numbers!
35/49
Let's analyze the given code:
✅ Corrected Version:
If the intent was to reverse the string 'abcd' , join the characters, and then print each
character, the correct version is:
python
for i in "".join(reversed(list('abcd'))):
print(i)
"".join(...) → 'dcba'
python
for i in 'dcba':
print(i)
36/49
✅ Output:
css
d
c
b
a
You cannot modify, insert, or delete individual characters directly from a string. Instead,
operations that appear to "change" a string actually return a new string.
s = "hello"
s[0] = 'H' # ❌ This will raise an error
Output:
php
37/49
✅ String Manipulation in Python
Even though strings are immutable, Python provides many string methods to create new
modified strings.
1. Concatenation
python
s1 = "Hello"
s2 = "World"
result = s1 + " " + s2
print(result) # Output: Hello World
2. Slicing
python
s = "Python"
print(s[0:3]) # Output: Pyt
print(s[-1]) # Output: n
3. Uppercase / Lowercase
python
s = "hello"
print(s.upper()) # Output: HELLO
print(s.lower()) # Output: hello
4. Replace
38/49
python
s = "a,b,c"
parts = s.split(",") # ['a', 'b', 'c']
joined = "-".join(parts) # 'a-b-c'
print(joined)
✅ Summary
Operation Method Used Example
39/49
Operation Method Used Example
So while strings themselves can’t be modified in-place, Python gives us powerful tools to
manipulate and create new strings easily.
bash
python
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
40/49
# Extract title
print(soup.title.string)
bash
bash
python
41/49
bash
python
driver = webdriver.Chrome()
driver.get('https://example.com')
print(driver.title)
driver.quit()
2. Send a request
Use requests.get(URL)
42/49
4. Extract the data
Let me know if you want a full working example for a real website (e.g., job listings, news,
products)!
To scrape multiple pages of a website using Python, you typically follow a pattern of
iterating through paginated URLs and extracting the desired content from each page.
arduino
https://example.com/products?page=1
https://example.com/products?page=2
...
✅ Code:
43/49
python
import requests
from bs4 import BeautifulSoup
python
import csv
44/49
for page in range(1, 6):
url = f'https://example.com/products?page={page}'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
products = soup.find_all('h2', class_='product-title')
for product in products:
writer.writerow([product.text.strip()])
🧠 Tips:
Add time.sleep(1) between requests to avoid overloading the server.
Let Me Know:
If you give me a sample URL pattern, I can write a custom scraper for it.
Here’s a complete Python program to download all images from a web page using
requests , BeautifulSoup , and urllib .
✅ Prerequisites
Install the required libraries (if not already):
bash
45/49
✅ Python Code
python
import requests
from bs4 import BeautifulSoup
import os
from urllib.parse import urljoin
import shutil
try:
img_data = requests.get(img_url, stream=True)
if img_data.status_code == 200:
with open(f"downloaded_images/{filename}", 'wb') as f:
shutil.copyfileobj(img_data.raw, f)
print(f"Downloaded: {filename}")
46/49
except Exception as e:
print(f"Failed to download {img_url} - {e}")
✅ How It Works
1. Asks for the webpage URL
🧠 Notes:
This works for static image URLs (not dynamically loaded by JavaScript).
Would you like a version that uses Selenium for dynamic websites too?
You can easily create and view HTML files using Python by writing HTML content into a
.html file and then opening it in a web browser.
✅ Step-by-Step Guide
47/49
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>My First HTML Page</title>
</head>
<body>
<h1>Hello from Python!</h1>
<p>This is a sample HTML file created using Python.</p>
</body>
</html>
"""
python
import webbrowser
✅ Full Program
python
import webbrowser
html_content = """
<!DOCTYPE html>
48/49
<html>
<head>
<title>Generated Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This HTML file was generated using Python.</p>
</body>
</html>
"""
file_path = "sample.html"
# Open in browser
webbrowser.open(file_path)
🧠 Notes:
You can customize html_content with any valid HTML code.
49/49