0% found this document useful (0 votes)
3 views46 pages

Python Programs

pPython programs
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)
3 views46 pages

Python Programs

pPython programs
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

USERBIO-DATA FORMATTER

PROGRAM:
# User Bio-Data Formatter

# Step 1: Accept user inputs


name = input("Enter your full name: ")
age = input("Enter your age: ")
gender = input("Enter your gender: ")
qualification = input("Enter your highest qualification: ")
hobbies = input("Enter your hobbies (comma separated): ")
email = input("Enter your email ID: ")
phone = input("Enter your phone number: ")
address = input("Enter your address: ")

# Step 2: Format the bio-data using multiline string


profile_card = f"""
========================================
USER BIO-DATA
========================================
Name : {name}
Age : {age}
Gender : {gender}
Qualification : {qualification}
Hobbies : {hobbies}
Email ID : {email}
Phone Number : {phone}
Address : {address}
Address :{address}
========================================
"""
#Step3:Display the formatted bio-data
print(profile_card)
OUTPUT:
Enter your full name: Grace Cathrine V
Enter your age: 23
Enter your gender: Female
Enter your highest qualification: B.E
Enter your hobbies (comma separated): Drawing,
Music
Enter your email ID: gracecathy@[Link]
Enter your phone number: 8756342123
Enter your address: Kamaraj Nagar, Avadi,
Chennai – 600062
========================================
USER BIO-DATA
========================================
Name :GraceCathrineV
Age 23
Gender :Female
Qualification: B.E
Hobbies :Drawing, Music
Email ID
:gracecathy@[Link]
Phone Number 8756342123
Address :KamarajNagar,Avadi,Chennai-600062
========================================

RESULT:
The program successfully collects user details and formats them into a structured and
readable bio-data profile card using Python’s multiline string formatting..
MATHOPERATIONSDEMO

PROGRAM:
importmathasm
import random

r1=[Link](5,15) a
= [Link](r1)

#Angleindegrees
angle_rad=[Link](r1)#Convertto radians

# Trigonometric Functions
sin_val= [Link](angle_rad)
cos_val=[Link](angle_rad)
tan_val=[Link](angle_rad)

#LogarithmicFunctions
num = 10
log_e = [Link](num) #Naturallog(basee)
log_10 = m.log10(num) # Log base 10

# Exponential Functions
exp_val = [Link](2) #e^2
power_val=[Link](2, 5)#2raisedto5
# Output Results
print("==== Math Operations Demo ====\n")

print("Square root of {} is : {:.2f}".format(r1, a))

print(f"Angle : {r1} degrees = {angle_rad:.4f} radians")

print(f"sin({r1}) = {sin_val:.4f}")
print(f"cos({r1}) = {cos_val:.4f}")
print(f"tan({r1}) = {tan_val:.4f}\n")

print(f"Natural log of {num} : {log_e:.4f}")


print(f"Log base 10 of {num} : {log_10:.4f}\n")

print(f"Exponential of 2 (e^2) : {exp_val:.4f}")


print(f"2 raised to power 5 : {power_val:.4f}")
OUTPUT:
====Math Operations Demo====
Square root of 5 is : 2.24
Angle: 5 degrees0.0873radians
sin(5)= 0.0872
cos(5) =0.9962
tan(5)=0.0875

Natural log of 10 : 2.3026


Logbase10 of 10 : 1.0000

Exponential of 2(e^2) : 7.3891


2raised to power 5 : 32.0000

RESULT:
The program successfully demonstrates the use of trigonometric , logarithmic , and exponential
functions using the math module in Python.
CONVERSIONAPP

PROGRAM:
# Conversion Functions

def celsius_to_fahrenheit(c):
return (c * 9/5) + 32

def fahrenheit_to_celsius(f):
return (f - 32) * 5/9

def meters_to_feet(m):
return m * 3.28084

def feet_to_meters(ft):
return ft / 3.28084

def kg_to_pounds(kg):
return kg * 2.20462

def pounds_to_kg(lb):
return lb / 2.20462
# Menu-driven Conversion App
print("==== CONVERSION APP ====")

print("1. Celsius to Fahrenheit")


print("2. Fahrenheit to Celsius")
print("3. Meters to Feet")
print("4. Feet to Meters")
print("[Link]")
print("[Link]")

choice = int(input("Enter your choice (1-6): "))


value=float(input("Enter the value to convert:"))

ifchoice == 1:
result =celsius_to_fahrenheit(value)
print(f"{value}°C={result:.2f}°F")
elifchoice ==2:
result =fahrenheit_to_celsius(value)
print(f"{value}°F={result:.2f}°C")
elifchoice ==3:
result = meters_to_feet(value)
print(f"{value}meters={result:.2f}feet")
elifchoice ==4:
result = feet_to_meters(value)
print(f"{value}feet={result:.2f}meters")
elifchoice ==5:
result = kg_to_pounds(value)
print(f"{value}kg={result:.2f}pounds")
elifchoice ==6:
result = pounds_to_kg(value)
print(f"{value}pounds={result:.2f}kg")
else:
print("Invalidchoice!")
OUTPUT:
==== CONVERSION APP ====
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
3. Meters to Feet
4. Feet to Meters
5. Kilograms to Pounds
6. Pounds to Kilograms

Enter your choice (1-6): 1


Enter the value to convert: 100

100.0°C = 212.00°F
==== CONVERSION APP ====

1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
3. Meters to Feet
4. Feet to Meters
5. Kilograms to Pounds
6. Pounds to Kilograms

Enter your choice (1-6): 5


Enter the value to convert: 100

100.0 kg = 220.46 pounds

RESULT:
The program successfully converts temperature, length, and mass between commonly used unit pairs
with accurate calculations and formatted outputs.
PATTERNPRINTINGUSINGRECURSION

PROGRAM:

# Recursive Function for Star Pyramid

def star_pyramid(n, i=1):

if i > n:

return

print(' ' * (n - i) + '*' * (2 * i - 1))

star_pyramid(n, i + 1)

# Recursive Function for Hollow Pyramid

def hollow_pyramid(n, i=1):

if i > n:

return

if i == 1:

print(' ' * (n - i) + '*')


elif i == n:

print('*' * (2 * i - 1))

else:

print(' ' * (n - i) + '*' + ' ' * (2 * i - 3) + '*')

hollow_pyramid(n, i + 1)
# Recursive Function for Diamond Pattern

def diamond(n):

def upper_half(i):

if i > n:

return

print(' ' * (n - i) + '*' * (2 * i - 1))

upper_half(i + 1)

def lower_half(i):

if i == 0:

return

print(' ' * (n - i) + '*' * (2 * i - 1))

lower_half(i - 1)

upper_half(1)

lower_half(n - 1)

# Recursive Function for Number Triangle

def number_triangle(n, i=1):

def print_nums(k=1):
if k > i:

return

print(k,end='')

print_nums(k+ 1)

ifi>n:

return

print_nums()

print()

number_triangle(n,i+1)

#RecursivefunctionforAlphabetTriangle def

alphabet_triangle(n, i=1):

defprint_chars(ch=65):

if ch >= 65 + i:

return

print(chr(ch),end='')

print_chars(ch + 1)

ifi>n:

return

print_chars()
print()
alphabet_triangle(n, i + 1)

# Main Menu

levels = 5

print("Star Pyramid:")

star_pyramid(levels)

print("\nHollow Pyramid:")

hollow_pyramid(levels)

print("\nDiamond using Stars:")

diamond(levels)

print("\nNumber Triangle:")

number_triangle(levels)

print("\nAlphabet Triangle:")

alphabet_triangle(levels)
OUTPUT:

StarPyramid:

***

*****

*******

*********

HollowPyramid:

**

**

* *

*********

DiamondusingStars:

***

*****

*******

*********
*******

*****

***

NumberTriangle:

12

123

1234

12345

AlphabetTriangle:

AA

AB C

ABC

DAB C

DE

RESULT:

The program correctly prints recursive patterns including pyramids, triangles, and diamond
shapes using stars, numbers, and alphabets..
PRODUCTINVENTORYUSING2DTUPLES

PROGRAM:

inventory=(

(101,"Mouse",50, 299.0),

(102,"Keyboard",30, 499.0),

(103,"Monitor", 20, 7999.0),

(104,"CPU",10,15499.0),

(105,"Webcam", 15, 999.0),

(106,"Speaker",25,1999.0)

def search_product(name):

found = False

for product in inventory:

if product[1].lower() == [Link]():

print(f"\nProduct Found:")
print(f"ID : {product[0]}")
print(f"Name : {product[1]}")
print(f"Quantity : {product[2]}")
print(f"Price : {product[3]:.2f}")

found = True
break

if not found:
print("Product not found.")
print("Product not found.")

def sort_by_price():

sorted_inventory = sorted(inventory, key=lambda x: x[3])

print("\nProducts Sorted by Price:")

print("{:<10} {:<15} {:<10} {:<10}".format(


"ID", "Name", "Quantity", "Price"
))

for product in sorted_inventory:

print("{:<10} {:<15} {:<10} {:<10.2f}".format(


product[0],
product[1],
product[2],
product[3]
))

# Main Menu
while True:

print("\n=== Product Inventory Menu ===")


print("1. Search Product by Name")
print("2. Sort and Display by Price")
print("3. Exit")

choice = input("Enter your choice: ")

if choice == "1":

name = input("Enter product name to search: ")


search_product(name)

elif choice == "2":

sort_by_price()
elif choice == "3":

print("Exiting program.")

break

else:

print("Invalid [Link].")
OUTPUT:

=== Product Inventory Menu ===

1. Search Product by Name


2. Sort and Display by Price
3. Exit

Enter your choice: 1

Enter product name to search: cpu

Product Found:

ID : 104
Name : CPU
Quantity : 10
Price : 15499.00

=== Product Inventory Menu ===

1. Search Product by Name


2. Sort and Display by Price
3. Exit

Enter your choice: 2

Products Sorted by Price:


ID Name Quantity Price

101 Mouse 50 2299.0


0
102 30 2499.00
Keyboad
105 15 2999.00
Webcam
106 Speaker 25 21999.00

103 Monitor 20 27999.00


104 CPU 10 215499.00

===Product InventoryMenu ===

1. Search Product by Name


2. Sort and Display by Price
3. Exit

Enter your choice: 3

Exiting program.

RESULT:
The program successfully uses a 2D tuple to store product inventory, allows searching by name, and
displays sorted results by price using formatted output.
MULTI-SUBJECTQUIZUSING DICTIONARY

PROGRAM:

# Multi-Subject Quiz using Nested Dictionaries

# Quiz data
quiz_bank = {

"Math": {
"What is 5 + 3?" : "8",
"What is the square root of 49?" : "7",
"What is 10 * 2?" : "20"
},

"Science": {
"What planet is known as the Red Planet?" : "Mars",
"What gas do plants absorb from the atmosphere?" : "Carbon Dioxide",
"What is the boiling point of water (in Celsius)?" : "100"
},

"History": {
"Who was the first President of the USA?" : "George Washington",
"In which year did World War II end?" : "1945",
"Who was known as the Iron Lady?" : "Margaret Thatcher"
}
}

# Display subjects
print("Available Subjects:")

for subject in quiz_bank:


print(f"- {subject}")

# User selects subject


chosen_subject = input(
"\nEnter the subject you want to take a quiz on: "
).title()

# Validate subject
if chosen_subject in quiz_bank:
questions = quiz_bank[chosen_subject]
score = 0

print(f"\n{chosen_subject} Quiz - Answer the following questions:\n")

for question, correct_answer in [Link]():

user_answer = input(question + " ").strip()

if user_answer.lower() == correct_answer.lower():

print("Correct!\n")
score += 1

else:

print(f"Wrong! The correct answer is: {correct_answer}\n")

total = len(questions)

print(f"You scored {score} out of {total} in {chosen_subject}.\n")

else:
print("Invalid subject selected...")
OUTPUT:

Available Subjects:

- Math
- Science
- History

Enter the subject you want to take a quiz on: MATH

Math Quiz - Answer the following questions:

What is 5 + 3? 8
Correct!

What is the square root of 49? 7


Correct!

What is 10 * 2? 20
Correct!

You scored 3 out of 3 in Math.


CONTACTMANAGER

PROGRAM:
# Contact Manager Program

# Step 1: Accept initial list of names


contacts = []

n = int(input("How many contacts do you want to enter? "))

for i in range(n):

name = input(f"Enter contact {i+1}: ")


[Link]([Link]())

# Step 2: Menu for operations


def display_menu():

print("\n=== Contact Manager Menu ===")


print("1. Add New Contact")
print("2. Update Contact")
print("3. Search Contact")
print("4. Sort Contacts Alphabetically")
print("5. Display All Contacts")
print("6. Exit")

while True:

display_menu()

choice = input("Enter your choice (1-6): ")

if choice == "1":

new_contact = input("Enter new contact name: ").strip()


[Link](new_contact)

print("Contact added...")

elif choice == "2":

old_name = input("Enter the name to update: ").strip()


if old_name in contacts:

new_name = input("Enter the new name: ").strip()

index = [Link](old_name)
contacts[index] = new_name

print("Contact updated.")

else:

print("Contact not found.")

elif choice == "3":

search_name = input("Enter the name to search: ").strip()

if search_name in contacts:

print(f"{search_name} is in your contact list.")

else:

print("Contact not found.")

elif choice == "4":

[Link]()

print("Contacts sorted alphabetically.")

elif choice == "5":

print("\nYour Contact List:")

for contact in contacts:


print("- " + contact)

elif choice == "6":

print("Exiting Contact Manager.")


break
else:

print("Invalid choice. Please try again.")


OUTPUT:
How many contacts do you want to enter? 3

Enter contact 1: SANTHI


Enter contact 2: RAJU
Enter contact 3: CATHY

=== Contact Manager Menu ===

1. Add New Contact


2. Update Contact
3. Search Contact
4. Sort Contacts Alphabetically
5. Display All Contacts
6. Exit

Enter your choice (1-6): 5

Your Contact List:

- SANTHI
- RAJU
- CATHY

=== Contact Manager Menu ===

1. Add New Contact


2. Update Contact
3. Search Contact
4. Sort Contacts Alphabetically
5. Display All Contacts
6. Exit

Enter your choice (1-6): 1

Enter new contact name: GRACE

Contact added...

=== Contact Manager Menu ===

1. Add New Contact


2. Update Contact
3. Search Contact
4. Sort Contacts Alphabetically
5. Display All Contacts
6. Exit

Enter your choice (1-6): 5

Your Contact List:

- SANTHI
- RAJU
- CATHY
- GRACE

=== Contact Manager Menu ===

1. Add New Contact


2. Update Contact
3. Search Contact
4. Sort Contacts Alphabetically
5. Display All Contacts
6. Exit

Enter your choice (1-6): 2

Enter the name to update: SANTHI


Enter the new name: KAVITHA

Contact updated.

=== Contact Manager Menu ===

1. Add New Contact


2. Update Contact
3. Search Contact
4. Sort Contacts Alphabetically
5. Display All Contacts
6. Exit

Enter your choice (1-6): 5

Your Contact List:


- KAVITHA
- RAJU
- CATHY
- GRACE

=== Contact Manager Menu ===

1. Add New Contact


2. Update Contact
3. Search Contact
4. Sort Contacts Alphabetically
5. Display All Contacts
6. Exit

Enter your choice (1-6): 3

Enter the name to search: RANI

Contact not found.

=== Contact Manager Menu ===

1. Add New Contact


2. Update Contact
3. Search Contact
4. Sort Contacts Alphabetically
5. Display All Contacts
6. Exit

Enter your choice (1-6): 3

Enter the name to search: GRACE

GRACE is in your contact list.

=== Contact Manager Menu ===

1. Add New Contact


2. Update Contact
3. Search Contact
4. Sort Contacts Alphabetically
5. Display All Contacts
6. Exit
Enter your choice (1-6): 4

Contacts sorted alphabetically.

=== Contact Manager Menu ===

1. Add New Contact


2. Update Contact
3. Search Contact
4. Sort Contacts Alphabetically
5. Display All Contacts
6. Exit

Enter your choice (1-6): 5

Your Contact List:

- CATHY
- GRACE
- KAVITHA
- RAJU

=== Contact Manager Menu ===

1. Add New Contact


2. Update Contact
3. Search Contact
4. Sort Contacts Alphabetically
5. Display All Contacts
6. Exit

Enter your choice (1-6): 6

Exiting Contact Manager.

RESULT:
The program successfully accepts and stores a list of contact names and allows the user to update,
search, and sort them using Python list method
WORDFORMATTERANDANALYZER

PROGRAM:

def clean_spaces(text): def

clean_spaces(text):

return ''.join([Link]())

def

count_substring(sentence,

sub):

return

[Link](sub)

def is_palindrome(word):

return [Link]() ==

[Link]()[::-1]

def
count_palindromes(word

s):

return sum(

1 for word in words

if is_palindrome(word)

and len(word) > 1

def

count_anagrams(words):

seen = {}

count = 0

for word in words:

sorted_word =

''.join(sorted([Link](

)))

if sorted_word in seen:
count +=

seen[sorted_word]

seen[sorted_word]

+= 1

else:

seen[sorted_word] =

return count

def modify(sentence):

word_to_replace =

input("Enter the word to

replace: ")

new_word = input("Enter

the new word: ")

replaced_sentence =

[Link](
word_to_replace,

new_word

return replaced_sentence

# Main Program

sentence = input("Enter a

sentence: ")

# Remove unwanted spaces

cleaned_sentence =

clean_spaces(sentence)

# Count substring

substring = input("Enter a

substring to count: ")

substring_count =

count_substring(sentence,

substring)
# Split words

words =

cleaned_sentence.split()

# Count palindrome words

palindrome_count =

count_palindromes(word

s)

# Count anagram word pairs

anagram_pair_count =

count_anagrams(words)

# Change substring

modify_res =

modify(sentence)

# Output all results

print("\nProcessed

Results:")

print("Cleaned Sentence:",
cleaned_sentence)

print(f"Number of times

'{substring}' appears:",

substring_count)

print("Number of

palindrome words:",

palindrome_count)

print("Number of anagram

word pairs:",

anagram_pair_count)

print("Changed substring:",

modify_res)
OUTPUT:

Enter a sentence:
I AM GOING TO POST MALAYALAM ARTICLE

Enter a substring to count:


POST

Enter the word to replace:


GOING

Enter the new word:


GO

Processed Results:

Cleaned Sentence:
IAMGOINGTOPOSTMALAYALAMARTICLE

Number of times 'POST' appears: 1

Number of palindrome words: 1

Number of anagram word pairs: 0

Changed substring:
I AM GO TO POST MALAYALAM ARTICLE

RESULT:
The program successfully replaces words, removes extra spaces, counts substring occurrences, and
identifies palindromes and anagram pairs from a given sentence.
TEXTPROCESSINGANDANALYSISUSING PYTHON

PROGRAM:
import pandas as pd

# Step 1: Create employee salary data


data = {
"Emp_ID": [101, 102, 103, 104, 105, 106, 107],

"Name": [
"Alice",
"Bob",
"Charlie",
"David",
"Eva",
"Frank",
"Grace"
],

"Salary": [
50000,
55000,
48000,
62000,
58000,
51000,
53000
]
}

# Step 2: Convert to DataFrame


df = [Link](data)

# Step 3: Write to Excel


excel_file = "employee_salary.xlsx"

df.to_excel(excel_file, index=False)

# Step 4: Read from Excel


read_df = pd.read_excel(excel_file)

# Step 5: Display top 5 records


print("Top 5 Employee Records:\n")

print(read_df.head())

# Step 6: Calculate total salary payout


total_salary = read_df["Salary"].sum()

print(f"\nTotal Salary Payout: ₹{total_salary}")


OUTPUT:
Top5EmployeeRecords:

Emp_ID NameSalary
0 101 Alice50000
1 102 Bob55000
2 103Charlie48000
3 104 David62000
4 105 Eva58000

TotalSalaryPayout:₹377000

RESULT:
The program successfully writes employee salary data to an Excel file, reads the file to display
the top 5 records, and calculates the total salary payout using Python's pandas library..
NUMERICALANALYSISUSINGNUMPYANDSCIPY

PROGRAM:
import numpy as np

# Step 1: Create a NumPy array of student marks


# (5 students, 5 subjects)

marks = [Link]([
[85, 90, 78, 92, 88],
[76, 85, 83, 80, 79],
[90, 88, 84, 91, 86],
[65, 70, 72, 68, 74],
[88, 82, 85, 87, 89]
])

# Step 2: Perform numerical operations

mean_all = [Link](marks)

median_all = [Link](marks)

max_all = [Link](marks)

min_all = [Link](marks)

mean_per_student = [Link](marks, axis=1)

mean_per_subject = [Link](marks, axis=0)

# Flatten into 1 row and 25 columns


reshaped = [Link](1, 25)

# Step 3: Display results

print("Original Marks Array (5 students × 5 subjects):")

print(marks)

print("\nMean of all marks:", mean_all)

print("Median of all marks:", median_all)


print("Maximum mark:", max_all)

print("Minimum mark:", min_all)

print("\nMean marks per student:", mean_per_student)

print("Mean marks per subject:", mean_per_subject)

print("\nReshaped Array (1 row, 25 columns):")

print(reshaped)
OUTPUT:

RESULT:
The program successfully demonstrates how different chart types can be used to visualize
monthly temperature variations using matplotlib and seaborn.

You might also like