Python Pratical 1-15 Program
Python Pratical 1-15 Program
PROGRAM:
print("\t\tTemperature Conversion")
choice = int(input("1. Celsius to Fahrenheit\n2. Fahrenheit to Celsius\nEnter your
choice: "))
if choice == 1:
celsius = float(input("Enter temperature in Celsius: "))
# Calculate Fahrenheit
fahrenheit = (celsius * 9/5) + 32
print('%0.2f Degree Celsiuus Is Equal To %0.2f dDegree
Fahrenheit'%(celsius,fahrenheit))
elif choice == 2:
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
# Calculate Celsius
celsius = (fahrenheit - 32) * 5/9
print('%0.2f degree Fahrenheit is equal to %0.2f degree Celsius'%(fahrenheit,
celsius))
else:
print("Invalid option")
OUTPUT:
RUN1:
Temperature Conversion
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Enter your choice: 1
Enter temperature in Celsius: 40
40.00 Degree Celsiuus Is Equal To 104.00 dDegree Fahrenheit
RUN2:
Temperature Conversion
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Enter your choice: 2
Enter temperature in Fahrenheit: 98
98.00 degree Fahrenheit is equal to 36.67 degree Celsius
RUN3:
Temperature Conversion
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Enter your choice: 3
Invalid option
1(b).Python program to construct the following pattern, using a nested loop.
PROGRAM:
def pyramid_pattern(rows):
for i in range(rows):
for j in range(rows - i - 1):
print(" ", end="")
for k in range(2 * i + 1):
print("*", end="")
print()
def look_up_word(dictionary):
word = input("Enter the word to look up: ").lower()
meaning = dictionary.get(word, "Word not found in the dictionary.")
print(f"Meaning of '{word}': {meaning}")
def add_word(dictionary):
word = input("Enter the new word: ").lower()
meaning = input(f"Enter the meaning of '{word}': ")
dictionary[word] = meaning
print(f"'{word}' added to the dictionary.")
def main():
my_dictionary = {} # Initialize an empty dictionary
while True:
display_menu()
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
look_up_word(my_dictionary)
elif choice == '2':
add_word(my_dictionary)
elif choice == '3':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
if __name__ == "__main__":
main()
OUTPUT:
Menu:
1. Look up a word
2. Add a new word and its meaning
3. Exit
Enter your choice (1/2/3): 2
Enter the new word: accept
Enter the meaning of 'accept': agree to take
'accept' added to the dictionary.
Menu:
1. Look up a word
2. Add a new word and its meaning
3. Exit
Enter your choice (1/2/3): 1
Enter the word to look up: accept
Meaning of 'accept': agree to take
Menu:
1. Look up a word
2. Add a new word and its meaning
3. Exit
Enter your choice (1/2/3): 3
Exiting the program. Goodbye!
10.Design a simple Tkinter GUI that includes a button and displays a message
when the button is clicked.
PROGRAM:
import tkinter as tk
from tkinter import messagebox
def on_button_click():
messagebox.showinfo("Message", "Button clicked!")
root = tk.Tk()
root.title("Simple Tkinter GUI")
root.mainloop()
OUTPUT:
11.Develop a program that accesses the Facebook Messenger API and retrieves
message data.
PROGRAM:
import facebook as fb
access_token="EAAGwYBiLqIcBO1ZAWiurQx88u0yFhZBMwA48OfZBuIeTySvqhDB
J1OgJmFzPzZAOwEy2w3ZAI4GBj2oFF4S4PmIVj92rCSAOXYAGESFvZCUf3pS41Y
vWgFsw3QEqCZAUsZCdMrvFl8MMZBmBmU5ZAbrnODZAi42sQS1HFzXwv5fMQy
W22jKXyf9kJ6WUXWcaL0YmfSwU2sKJmORfb9SILHy9oTBIDaC2M8ZD"
asafb=fb.GraphAPI(access_token)
print(asafb.get_object("475401751865479_122104693370425765"))
OUTPUT:
{'created_time': '2024-07-26T11:18:32+0000', 'message':
'This is sample post!', 'id':
'342933882244311_122104693370425765'}
12.Create a Python script that utilizes the Openweather API to get current
weather information.
PROGRAM:
import requests
API_KEY = '3e6148b70c7b4a78dcdbd9eda91d33be'
def get_current_weather(city):
url=f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KE
Y}&units=metric'
try:
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(f"Weather in {city}:")
print(f"Description: {data['weather'][0]['description']}")
print(f"Temperature: {data['main']['temp']}°C")
print(f"Humidity: {data['main']['humidity']}%")
print(f"Wind speed: {data['wind']['speed']} m/s")
else:
print(f"Error fetching data: {response.status_code}")
except Exception as e:
print(f"Error fetching data: {str(e)}")
city = input("Enter city name: ")
get_current_weather(city)
OUTPUT:
Enter city name: Melbourne
Weather in Melbourne:
Description: mist
Temperature: 25.76°C
Humidity: 88%
Wind speed: 6.17 m/s
13. Write a program that uses to analyze a dataset using Pandas, including
operations like filtering and grouping.
PROGRAM:
import pandas as pd
file_path = 'sales_data.csv'
df = pd.read_csv(file_path)
print("First 5 rows of the dataset:")
print(df.head())
print("\nSummary statistics:")
print(df.describe())
print("\nFiltering data for Product 'A':")
product_a_data = df[df['Product'] == 'A']
print(product_a_data)
print("\nGrouping data by Product:")
product_summary = df.groupby('Product').agg({
'Units Sold': 'sum',
'Revenue': 'sum'
}).reset_index()
print(product_summary)
print("\nProducts sorted by Revenue (descending):")
sorted_products = product_summary.sort_values(by='Revenue', ascending=False)
print(sorted_products)
OUTPUT:
First 5 rows of the dataset:
Date Product Units Sold Revenue
0 2024-01-01 A 100 500
1 2024-01-02 B 150 750
2 2024-01-03 A 80 400
3 2024-01-04 C 120 900
4 2024-01-05 B 200 1000
Summary statistics:
Units Sold Revenue
count 10.000000 10.000000
mean 127.500000 727.500000
std 40.637284 264.167981
min 80.000000 400.000000
25% 96.250000 512.500000
50% 115.000000 675.000000
75% 150.000000 900.000000
max 200.000000 1200.000000
Filtering data for Product 'A':
Date Product Units Sold Revenue
0 2024-01-01 A 100 500
2 2024-01-03 A 80 400
6 2024-01-07 A 110 550
9 2024-01-10 A 95 475
Grouping data by Product:
Product Units Sold Revenue
0 A 385 1925
1 B 530 2650
2 C 360 2700
Products sorted by Revenue (descending):
Product Units Sold Revenue
2 C 360 2700
1 B 530 2650
0 A 385 1925
14. Develop a program that utilizes NumPy for numerical operations on arrays.
PROGRAM:
import numpy as np
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([6, 7, 8, 9, 10])
print("Array 1:", arr1)
print("Array 2:", arr2)
print("\nBasic operations:")
print("Addition (arr1 + arr2):", arr1 + arr2)
print("Subtraction (arr2 - arr1):", arr2 - arr1)
print("Multiplication (arr1 * arr2):", arr1 * arr2)
print("Division (arr2 / arr1):", arr2 / arr1)
print("Square root (np.sqrt(arr1)):", np.sqrt(arr1))
print("Sum of elements in arr2:", np.sum(arr2))
print("Mean of elements in arr1:", np.mean(arr1))
print("Maximum element in arr2:", np.max(arr2))
arr3 = np.array([[1, 2, 3], [4, 5, 6]])
print("\nOriginal array (2x3):")
print(arr3)
print("\nReshaped array (3x2):")
print(arr3.reshape(3, 2))
OUTPUT:
Array 1: [1 2 3 4 5]
Array 2: [ 6 7 8 9 10]
Basic operations:
Addition (arr1 + arr2): [ 7 9 11 13 15]
Subtraction (arr2 - arr1): [5 5 5 5 5]
Multiplication (arr1 * arr2): [ 6 14 24 36 50]
Division (arr2 / arr1): [6. 3.5 2.66666667 2.25 2.]
Square root (np.sqrt(arr1)): [1. 1.41421356 1.73205081 2. 2.23606798]
Sum of elements in arr2: 40
Mean of elements in arr1: 3.0
Maximum element in arr2: 10
Original array (2x3):
[[1 2 3]
[4 5 6]]
Reshaped array (3x2):
[[1 2]
[3 4]
[5 6]]
15.Design a data visualization program using matplotlib and seaborn to create
meaningful plots from a dataset.
PROGRAM:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
tips = sns.load_dataset('tips')
plt.figure(figsize=(8, 5))
plt.scatter(tips['total_bill'], tips['tip'], color='blue', alpha=0.5)
plt.title('Scatter Plot of Total Bill vs Tip')
plt.xlabel('Total Bill ($)')
plt.ylabel('Tip ($)')
plt.grid(True)
plt.tight_layout()
plt.show()
plt.figure(figsize=(8, 5))
sns.barplot(x='day', y='total_bill', data=tips, palette='viridis')
plt.title('Average Total Bill by Day')
plt.xlabel('Day of the Week')
plt.ylabel('Average Total Bill ($)')
plt.tight_layout()
plt.show()
plt.figure(figsize=(8, 5))
sns.boxplot(x='day', y='total_bill', data=tips, palette='pastel')
plt.title('Distribution of Total Bill by Day')
plt.xlabel('Day of the Week')
plt.ylabel('Total Bill ($)')
plt.tight_layout()
plt.show()
plt.figure(figsize=(8, 5))
sns.histplot(tips['total_bill'], bins=20, kde=True, color='purple')
plt.title('Distribution of Total Bill')
plt.xlabel('Total Bill ($)')
plt.ylabel('Frequency')
plt.tight_layout()
plt.show()
OUTPUT: