python record pdf
python record pdf
DATE:
AIM:
To develop python programs using operators with basic input and output operations.
PROGRAM 1:
OUTPUT:
PROGRAM 2:
import math
x1 = float(input("Enter x1: "))
y1 = float(input("Enter y1: "))
x2 = float(input("Enter x2: "))
y2 = float(input("Enter y2: "))
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print(f"The distance between the two points is: {distance:.2f}")
1
OUTPUT:
Enter x1: 2
Enter y1: 3
Enter x2: 6
Enter y2: 7
The distance between the two points is: 5.6
PROGRAM 3:
import math
radius = float(input("Enter radius of the circle: "))
area_circle = math.pi * radius ** 2
length = float(input("Enter length of the rectangle: "))
breadth = float(input("Enter breadth of the rectangle: "))
area_rectangle = length * breadth
base = float(input("Enter base of the triangle: "))
height = float(input("Enter height of the triangle: "))
area_triangle = 0.5 * base * height
side = float(input("Enter side of the square: "))
area_square = side * side
print(f"Area of Circle = {area_circle:.2f}")
print(f"Area of Rectangle = {area_rectangle:.2f}")
print(f"Area of Triangle = {area_triangle:.2f}")
print(f"Area of Square = {area_square:.2f}")
OUTPUT:
2
PROGRAM 4:
OUTPUT:
PROGRAM 5:
Write a program to calculate the total amount of money in the piggy bank,
given the coins of ₹10, ₹5, ₹2, and ₹1
OUTPUT:
PROGRAM 6:
Write a program to calculate the bill amount for an item given its quantity.
sold, value, discount, and tax
quantity = int(input("Enter quantity sold: "))
price = float(input("Enter price per item: "))
discount = float(input("Enter discount percentage: "))
tax = float(input("Enter tax percentage: "))
amount = quantity * price
3
discount_amount = amount * (discount / 100)
tax_amount = (amount - discount_amount) * (tax / 100)
total = amount - discount_amount + tax_amount
print(f"Total Bill Amount: ₹{total:.2f}")
OUTPUT
Enter quantity sold: 10
Enter price per item: 50
Enter discount percentage: 10
Enter tax percentage: 5
Total Bill Amount: ₹472.50
RESULT:
DEPARTMENT OF CSBS
Program 10
Output 5
Viva-Voce 5
Total 20
7
EX.NO: 02 CONTROL STATEMENTS
DATE:
AIM:
To develop python programs using control statements.
PROGRAM 1:
Develop a python program for finding the absolute value of a given number.
This is always measured as positive number. This number is the distance of
given number from the 0(Zero). The input value may be integer, float or
complex number in Python. The absolute value of given number may be integer
or float.
num = complex(input("Enter a number (real or complex): "))
abs_val = abs(num)
print(f"The absolute value of {num} is {abs_val}")
OUTPUT:
PROGRAM 2:
Calculate the Total selling price after levying the GST (Goods and Service Tax)
as CGST and SGST on sale. CGST (Central Govt. GST), SGST (State Govt.
GST) .
Sale amount CGST Rate SGST Rate
0-50000 5% 5%
Above 50000 18% 18%
sale_amount = float(input("Enter sale amount: "))
if sale_amount <= 50000:
cgst = sgst = 5
else:
cgst = sgst = 18
cgst_amt = sale_amount * cgst / 100
sgst_amt = sale_amount * sgst / 100
total_amount = sale_amount + cgst_amt + sgst_amt
print(f"\n--- GST Bill ---")
print(f"Sale Amount: ₹{sale_amount}")
print(f"CGST @ {cgst}%: ₹{cgst_amt}")
print(f"SGST @ {sgst}%: ₹{sgst_amt}")
print(f"Total Selling Price: ₹{total_amount}")
OUTPUT:
PROGRAM 3:
Write a Python program to construct the following pattern, using a nested for
loop. * * *
**
***
****
*****
****
***
**
*
OUTPUT:
*
**
***
****
*****
****
***
**
*
PROGRAM 4:
Write a Python program to guess a number between 1 and 9. Note : User is
prompted to enter a guess. If the user guesses wrong then the prompt appears
again until the guess is correct, on successful guess, user will get a "Well
guessed!" message, and the program will exit.
9
import random
number = random.randint(1, 9)
while True:
guess = int(input("Guess a number between 1 and 9: "))
if guess == number:
print("Well guessed!")
break
OUTPUT:
PROGRAM 5:
You have two streaming subscriptions and want to find out how much you
spend each month and how much you could save if you switch to paying
annually. Each subscription has a monthly cost and offers a discounted annual
rate. Write a Python program to calculate the total monthly cost for both
subscriptions, the total annual cost if you continue paying monthly, and
compare this with the annual rates you would pay if you switch to annual
payments. Finally, show how much you could save by choosing the annual
payment option.
Test Case:
Input:
Service 1 = $10/month
Service 2 = $12/month
Annual Discount for Service 1 = $100
Annual Discount for Service 2 = $120
Expected Output:
Monthly Total: $22.00
Total Annual Cost without Discount: $264.00
Total Annual Discounted Cost: $220.00
Total Savings: $44.00
s1_monthly = 10
s2_monthly = 12
s1_annual = 100
s2_annual = 120 10
monthly_total = s1_monthly + s2_monthly
annual_monthly_cost = monthly_total * 12
discounted_annual = s1_annual + s2_annual
savings = annual_monthly_cost - discounted_annual
print(f"Monthly Total: ${monthly_total:.2f}")
print(f"Total Annual Cost without Discount: ${annual_monthly_cost:.2f}")
print(f"Total Annual Discounted Cost: ${discounted_annual:.2f}")
print(f"Total Savings: ${savings:.2f}")
OUTPUT:
PROGRAM 6:
Write a Python program that iterates through integers from 1 to 50. For each
multiple of three, print "Fizz" instead of the number; for each multiple of five,
print "Buzz". For numbers that are multiples of both three and five, print
"FizzBuzz".
OUTPUT:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
RESULT:
Thus, python programs using control statements for different scenarios
were executed successfully.
DEPARTMENT OF CSBS
Program 10
Output 5
Viva-Voce 5
Total 20
EX.NO: 03 FUNCTIONS
DATE:
AIM:
To develop python programs using the concept of functions.
PROGRAM 1:
def calculate_ticket_price(age):
if age < 12:
return 5
elif age >= 60:
return 6
else:
return 10
print(calculate_ticket_price(8))
print(calculate_ticket_price(30))
print(calculate_ticket_price(65))
OUTPUT:
5
10
6
PROGRAM 2:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
print(celsius_to_fahrenheit(0)) # Output: 32.0
print(celsius_to_fahrenheit(37)) # Output: 98.6
OUTPUT:
32.0
98.6
PROGRAM 3:
You're creating a grading system. Given a score (0–100), return a letter grade:
A: 90+ , B: 80–89, C: 70–79, D: 60–69, F: below 60
Question: Write a function get_grade(score) that returns the letter grade.
Sample Input:
get_grade(85) # Output: "B"
get_grade(59) # Output: "F
def get_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
print(get_grade(85)) # Output: B
print(get_grade(59)) # Output: F
OUTPUT:
B
F
PROGRAM 4:
In a text editing app, users want a function that takes a sentence and reverses
17
each word, keeping the word order the same.
Question:
Write a function reverse_words(sentence) that reverses the characters of each
word.
Sample Input:
reverse_words("hello world") # Output: "olleh dlrow"
reverse_words("python is fun") # Output: "nohtyp si nuf"
def reverse_words(sentence):
words = sentence.split()
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words)
print(reverse_words("hello world"))
print(reverse_words("python is fun"))
OUTPUT:
PROGRAM 5:
PROGRAM 6:
import re
def is_strong_password(password):
if (len(password) >= 8 and
re.search(r'[A-Z]', password) and
re.search(r'[a-z]', password) and
re.search(r'[0-9]', password)):
return True
return False
print(is_strong_password("Password123"))
OUTPUT:
True
RESULT:
executed successfully.
DEPARTMENT OF CSBS
Program 10
Output 5
Viva-Voce 5
Total 20
EX.NO: 04 MODULES AND PACKAGES
DATE:
AIM:
To use modules and packages concepts in python for developing simple applications.
PROGRAM 1:
products = {
'P001': {'name': 'Pen', 'price': 10},
'P002': {'name': 'Notebook', 'price': 50},
'P003': {'name': 'Pencil', 'price': 5}
}
def get_product_info(pid):
return products.get(pid, None)
def generate_bill():
print("Available Products:")
for pid, details in products.items():
print(f"{pid}: {details['name']} - ₹{details['price']}")
PROGRAM 2:
import math
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Cannot divide by zero"
return x / y
def sqrt(x):
return math.sqrt(x) 21
def power(x, y):
return math.pow(x, y)
def scientific_calculator():
print("=== Scientific Calculator ===")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Square Root")
print("6. Power")
elif choice == 5:
x = float(input("Enter number: "))
print("Result:", sqrt(x))
else:
print("Invalid choice")
scientific_calculator()
22
OUTPUT:
RESULT:
Thus modules and packages concepts in python were used for developing simple applications
and verified successfully.
DEPARTMENT OF CSBS
Program 10
Output 5
Viva-Voce 5
Total 20
EX.NO: 05 STRING MANIPULATION
DATE:
AIM:
PROGRAM 1:
def is_valid_username(username):
return username.isalnum() and len(username) <= 12
print(is_valid_username("user123"))
print(is_valid_username("user@name"))
OUTPUT:
True
False
PROGRAM 2:
Email Masking for Privacy . You need to mask part of an email address when
displaying it publicly to protect user privacy. Write a program that takes an
email like [email protected] and returns a masked version like
jo****@example.com
def mask_email(email):
name, domain = email.split("@")
masked = name[:2] + "****@" + domain
return masked
print(mask_email("[email protected]"))
24
OUTPUT:
PROGRAM 3:
Detecting Palindromes You are building a text analyzer app. One of the
features is to detect if a word or phrase is a palindrome (ignoring spaces and
punctuation). Write a function that checks whether a given string is a
palindrome, ignoring case, spaces, and punctuation.
import re
def is_palindrome(text):
cleaned = re.sub(r'[^a-zA-Z0-9]', '', text).lower()
return cleaned == cleaned[::-1]
print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("Hello"))
OUTPUT:
True
False
PROGRAM 4:
Text Formatter for News Headlines - You’re building a news app that receives
article titles in random casing. You need to format the titles so each word starts
with a capital letter. Write a function that converts a given string like
"breaKing news: python is fun" to "Breaking News: Python Is Fun"
def format_headline(title):
return title.title()
print(format_headline("breaKing news: python is fun"))
OUTPUT:
25
PROGRAM 5:
Word Frequency Counter In a blog analysis tool, you need to find out how
often each word appears in a paragraph. Write a program that takes a block of
text and prints
def word_frequency(text):
words = text.lower().split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
for word, count in freq.items():
print(f"{word}: {count}")
paragraph = "Python is great and Python is fun"
word_frequency(paragraph)
OUTPUT:
RESULT:
Thus python programs for manipulating strings were written and executed
successfully.
DEPARTMENT OF CSBS
Program 10
Output 5
Viva-Voce 5
Total 20
EX.NO: 06 LIST AND TUPLE
DATE:
AIM:
To write python programs to perform various operations using lists and tuples.
PROGRAM 1:
Write a program to create a list and perform the following operations: append,
insert, delete, and update an element
OUTPUT:
PROGRAM 2:
Write a program to create a list of integers and print the largest, smallest, and
average of the list elements.
Largest: 89
Smallest: 12
Average: 47.2
PROGRAM 3:
OUTPUT:
PROGRAM 4:
Write a program to create a list of student names and sort them in ascending
and descending order.
OUTPUT:
OUTPUT:
PROGRAM 6:
Write a program to create a tuple, access its elements, and demonstrate tuple
immutability.
t = (1, 2, 3, 4)
print("Tuple:", t)
print("First Element:", t[0])
OUTPUT:
Tuple: (1, 2, 3, 4)
First Element: 1
RESULT:
Thus programs for various operations using lists and tuples in python were
written and executed successfully.
DEPARTMENT OF CSBS
Program 10
Output 5
Viva-Voce 5
Total 20
EX.NO: 07 SET AND DICTIONARY
DATE:
AIM:
To write python programs to perform various operations using sets and dictionaries.
PROGRAM 1:
Write a program to create a set and perform the following operations: Add an
element, remove an element, check for membership, and clear the set.
s = {1, 2, 3}
print("Original Set:", s)
s.add(4)
print("After Adding 4:", s)
s.remove(2)
print("After Removing 2:", s)
print("Is 3 in set?", 3 in s)
s.clear()
print("After Clearing:", s)
OUTPUT:
PROGRAM 2:
Write a program to take two sets of integers and perform the following
operations: Union, intersection, difference, and symmetric difference.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print("Union:", a | b)
print("Intersection:", a & b)
print("Difference (a - b):", a - b)
print("Symmetric Difference:", a ^ b)
OUTPUT:
PROGRAM 3:
OUTPUT:
PROGRAM 4:
Even numbers from 1 to 20: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
PROGRAM 5:
Write a program to create a dictionary with names and ages of 5 people and
print the dictionary.
people = {
"Alice": 25,
"Bob": 30,
"Cathy": 22,
"David": 28,
"Eva": 35
}
OUTPUT:
PROGRAM 6:
Write a program to search for a key in a dictionary and print its value if found.
OUTPUT:
RESULT:
Thus programs for various operations using sets and dictionaries in python
were written and executed successfully.
DEPARTMENT OF CSBS
Program 10
Output 5
Viva-Voce 5
Total 20
EX.NO: 08 EXCEPTION HANDLING
DATE:
AIM:
PROGRAM 1:
try:
num1 = float(input("Enter numerator: "))
num2 = float(input("Enter denominator: "))
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError:
print("Cannot divide by zero.")
OUTPUT:
Enter numerator: 10
Enter denominator: 2
Result: 5.0
PROGRAM 2:
Robust List Indexing: You’re developing a student report viewer. Users may
sometimes enter an invalid index to view a student’s mark. Write a program
that accesses an element from a predefined list of marks using an index
provided by the user. Use exception handling to catch IndexError and print
"Invalid index entered. Please try again."
40
marks = [75, 80, 92, 66, 88]
try:
index = int(input("Enter index to access marks: "))
print(f"Mark at index {index} is {marks[index]}")
except IndexError:
print("Invalid index entered. Please try again.")
OUTPUT:
Mark at index 2 is 92
PROGRAM 3:
Type-Safe Input for Integer Conversion: You’re building a data entry form.
Sometimes users enter text when a number is expected. Write a program
that takes user input and converts it to an integer. Handle ValueError using
a try-except block and print "Please enter a valid number." if the input is
not convertible.
try:
num = int(input("Enter an integer: "))
print(f"You entered: {num}")
except ValueError:
print("Please enter a valid number.")
OUTPUT:
Enter an integer: 25
You entered: 25
RESULT:
Thus exception handling concepts were used in python for simple scenarios and
executed successfully.
DEPARTMENT OF CSBS
Program 10
Output 5
Viva-Voce 5
Total 20