0% found this document useful (0 votes)
21 views

Python Pratical 1-15 Program

Python.

Uploaded by

malaiarasan037
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Python Pratical 1-15 Program

Python.

Uploaded by

malaiarasan037
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

1(a).Python Program to convert temperature in celsius to Fahrenheit.

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()

rows = int(input("Enter the number of rows: "))


pyramid_pattern(rows)
OUTPUT:
Enter the number of rows: 7
*
***
*****
*******
*********
***********
*************
2.Python program that prints prime numbers less than a given number n.
PROGRAM:
print("Prime numbers between 1 and n are:")
n=int(input("Enter n: "))
for num in range(2,n):
# prime numbers are greater than 1
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
OUTPUT:
Prime numbers between 1 and n are:
Enter n: 20
2
3
5
7
11
13
17
19
3.Program to fine the factorial of the given number using recursive function.
PROGRAM:
def fact(n):
if n==1:
return n
else:
return n*fact(n-1)
num=int(input("Enter a Number:"))
#check is the number is negavtive number
if num<0:
print("Sorry,Factorial does not exist for negative numbers")
elif num==0:
print("The factorial of 0 is 1")
else:
print("The Factorial of",num,"is",fact(num))
OUTPUT:
Enter a Number:5
The Factorial of 5 is 120
4.Python program to count the number of even and odd numbers from an array
of N numbers.
PROGRAM:
arr=[1,7,8,4,5,16,8]
n=len(arr)
countEven=0
countodd=0
for i in range(0, n):
if arr[i]%2==0 :
countEven += 1
else:
countodd += 1
print("Even Elements count : " )
print(countEven)
print("Odd Elements count : ")
print(countodd)
OUTPUT:
Even Elements count :
4
Odd Elements count :
3
5.Write a Python class to reverse a string word by word.
PROGRAM:
class py_reverse:
def revr(self, strs):
sp=strs.split()
sp.reverse()
res=" ".join(sp)
return res
str1=input("Enter a string with 2 or more words : ")
print("Reverse of string word by word: \n",py_reverse().revr(str1))
OUTPUT:
Enter a string with 2 or more words : Welcome to python programming
Reverse of string word by word:
programming python to Welcome
6.Given a tuple and a list as input, write a program to count the occurrences of
all items of the list in the tuple. (Input: tuple = ('a', 'a', 'c', 'b', 'd'), list = ['a', 'b'],
Output: 3)
PROGRAM:
def countOccurrence(tup, lst):
lst=set(lst)
return sum(1 for x in tup if x in lst)
tup = ('a', 'a', 'c', 'b', 'd')
lst = ['a', 'b']
print(countOccurrence(tup, lst))
OUTPUT:
3
7.Write a Python program for Towers of Hanoi using recursion.
PROGRAM:
def TowerOfHanoi(n, source, destination, auxiliary):
if n == 1:
print(f"Move disk 1 from source {source} to destination {destination}")
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print(f"Move disk {n} from source {source} to destination {destination}")
TowerOfHanoi(n-1, auxiliary, destination, source)
n=3
TowerOfHanoi(n,'A','B','C')
OUTPUT:
Move disk 1 from source A to destination B
Move disk 2 from source A to destination C
Move disk 1 from source B to destination C
Move disk 3 from source A to destination B
Move disk 1 from source C to destination A
Move disk 2 from source C to destination B
Move disk 1 from source A to destination B
8.Design and implement a simple Python program for a "Guess the Number"
game.
PROGRAM:
import random

print("Welcome to the Guessing Game!")


print("Try to guess the number I am thinking of between 1 and 10.")

number = random.randint(1, 10)


guess = -1

while guess != number:


guess = int(input("Enter your guess: "))
if guess < number:
print("Too low, try again.")
elif guess > number:
print("Too high, try again.")

print(f"Congratulations! You guessed the number {number} correctly!")


OUTPUT:
Welcome to the Guessing Game!
Try to guess the number I am thinking of between 1 and 10.
Enter your guess: 8
Too high, try again.
Enter your guess: 1
Too low, try again.
Enter your guess: 4
Congratulations! You guessed the number 4 correctly!
9.Create a menu driven Python program with a dictionary for words and their
meanings.
PROGRAM:
def display_menu():
print("\nMenu:")
print("1. Look up a word")
print("2. Add a new word and its meaning")
print("3. Exit")

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")

button = tk.Button(root, text="Click Me", command=on_button_click)


button.pack(pady=20)

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:

You might also like