0% found this document useful (0 votes)
26 views6 pages

8 10

The document contains Python programs to check if a given input is a palindrome using polymorphism and inheritance, download XKCD comics from online, read and write data to a spreadsheet, combine selected pages from multiple PDF files, and fetch weather data from a JSON file.

Uploaded by

shrinidhi N
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)
26 views6 pages

8 10

The document contains Python programs to check if a given input is a palindrome using polymorphism and inheritance, download XKCD comics from online, read and write data to a spreadsheet, combine selected pages from multiple PDF files, and fetch weather data from a JSON file.

Uploaded by

shrinidhi N
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/ 6

8.

a) Write a python program to find the whether the given input is palindrome or not (for both
string and integer) using the concept of polymorphism and inheritance.

class PalindromeChecker:
def is_palindrome(self, input_value):
raise NotImplementedError("Subclasses must implement this
method")

class StringPalindrome(PalindromeChecker):
def is_palindrome(self, input_value):
input_value = input_value.lower().replace(" ", "")
# Ignore case and spaces
return input_value == input_value[::-1]

class IntegerPalindrome(PalindromeChecker):
def is_palindrome(self, input_value):
return str(input_value) == str(input_value)[::-1]

def check_palindrome(palindrome_checker, input_value):


if palindrome_checker.is_palindrome(input_value):
return f"'{input_value}' is a palindrome."
else:
return f"'{input_value}' is not a palindrome."

if __name__ == "__main__":
input_value = input("Enter a string or an integer: ")

if input_value.isdigit():
checker = IntegerPalindrome()
else:
checker = StringPalindrome()

result = check_palindrome(checker, input_value)


print(result)
9
a) Write a python program to download the all XKCD comics

pip install requests


pip install IPython

PROGRAM
import os
import requests
from IPython.display import Image, display

def download_xkcd_comics(output_folder):
os.makedirs(output_folder, exist_ok=True)

url = 'https://xkcd.com/{}/info.0.json'
comic_number = 1
while True:
response = requests.get(url.format(comic_number))
if response.status_code == 200:
comic_data = response.json()
image_url = comic_data['img']
image_response = requests.get(image_url)

if image_response.status_code == 200:
image_name = os.path.basename(image_url)
image_path = os.path.join(output_folder,image_name)

with open(image_path, 'wb') as image_file:


image_file.write(image_response.content)

display(Image(filename=image_path))
else:
print(f"Failed to download image for comic
{comic_number}")
else:
break

comic_number += 1
if __name__ == "__main__":
output_folder = 'xkcd_comics'
download_xkcd_comics(output_folder)

9
b) Demonstrate python program to read the data from the spreadsheet and write the data in to
the spreadsheet

!pip install openpyxl

PROGRAM
import openpyxl

def read_spreadsheet(file_path):
workbook = openpyxl.load_workbook(file_path)
sheet = workbook.active

for row in sheet.iter_rows(min_row=2, values_only=True):


name, age, city = row
print(f"Name: {name}, Age: {age}, City: {city}")

workbook.close()

def write_spreadsheet(file_path):
workbook = openpyxl.Workbook()
sheet = workbook.active

sheet["A1"] = "Name"
sheet["B1"] = "Age"
sheet["C1"] = "City"

data = [
("A", 28, "Bangalore"),
("B", 32, "Mumbai"),
("C", 24, "Delhi")
]
for row in data:
sheet.append(row)

workbook.save(file_path)
workbook.close()

if __name__ == "__main__":
read_file_path = "C:\\Users\\DELL\\data.xlsx"
write_file_path = "C:\\Users\\DELL\\output.xlsx"

# Write data to a spreadsheet


write_spreadsheet(write_file_path)
print("Data written to spreadsheet.")

# Read data from a spreadsheet


read_spreadsheet(read_file_path)

10
a) Write a python program to combine select pages from many PDFs

pip install PyPDF2

PROGRAM
import PyPDF2

def combine_selected_pages(input_pdfs, output_pdf, selected_pages):


pdf_writer = PyPDF2.PdfWriter()

for pdf_file, page_numbers in zip(input_pdfs, selected_pages):


pdf_reader = PyPDF2.PdfReader(pdf_file)

for page_number in page_numbers:


if 1 <= page_number <= len(pdf_reader.pages):
page = pdf_reader.pages[page_number - 1]
pdf_writer.add_page(page)

with open(output_pdf, 'wb') as output_file:


pdf_writer.write(output_file)
# List of input PDFs, corresponding page numbers to select
input_pdfs = ['new.pdf', 'new1.pdf']
selected_pages = [[1, 3], [2]]

output_pdf = 'combined_pages.pdf'

combine_selected_pages(input_pdfs, output_pdf, selected_pages)


print(f'Selected pages from input PDFs combined and saved as
{output_pdf}')

10 b) Write a python program to fetch current weather data from the JSON file

A JSON (JavaScript Object Notation) file


1.Open a text editor that supports text editing.
2.Write the JSON data into the text editor. Ensure that the syntax adheres to the JSON format
rules.

3.JSON DATA TO BE SAVED


{
"city": "City Name",
"temperature": 70,
"conditions": "Sunny"
}
4.Save the file with a .json file extension. Choose an appropriate name for your JSON file. For
example, you can save it as data.json.
5. save the file in the same directory as your Python script
PROGRAM
import json

def fetch_weather_data(file_name):
try:
with open(file_name, 'r') as json_file:
weather_data = json.load(json_file)
return weather_data
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
return None
except json.JSONDecodeError:
print(f"Error: Invalid JSON format in '{file_name}'.")
return None

def display_weather_data(weather_data):
if weather_data is not None:
print("Weather Information:")
print(f"City: {weather_data['city']}")
print(f"Temperature: {weather_data['temperature']}°F")
print(f"Conditions: {weather_data['conditions']}")

# Fetch weather data from JSON file


file_name = 'data.json'
weather_data = fetch_weather_data(file_name)

# Display weather data


display_weather_data(weather_data)

You might also like