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

Python Prgm

The document contains various Python code snippets for calculating areas of geometric figures, simple interest, managing student records, checking if a number is even or odd, determining if a number is prime, generating multiplication tables, performing basic arithmetic operations, reading words of specific lengths from a text file, handling division exceptions, and implementing a shopping cart system using classes. Each section includes functions and user input prompts to demonstrate functionality. The code is structured to allow for interactive use and error handling.

Uploaded by

fg825589
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)
2 views

Python Prgm

The document contains various Python code snippets for calculating areas of geometric figures, simple interest, managing student records, checking if a number is even or odd, determining if a number is prime, generating multiplication tables, performing basic arithmetic operations, reading words of specific lengths from a text file, handling division exceptions, and implementing a shopping cart system using classes. Each section includes functions and user input prompts to demonstrate functionality. The code is structured to allow for interactive use and error handling.

Uploaded by

fg825589
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/ 5

1.

Calculate areas of geometric gures

import math

def calculate_area(shape, dimensions):


if shape == "circle":
return math.pi * dimensions[0] ** 2
elif shape == "rectangle":
return dimensions[0] * dimensions[1]
elif shape == "triangle":
return 0.5 * dimensions[0] * dimensions[1]

shape = input("Enter shape (circle, rectangle, triangle): ").lower()


if shape == "circle":
radius = oat(input("Enter radius: "))
print(f"Area: {calculate_area(shape, [radius]):.2f}")
elif shape == "rectangle":
length = oat(input("Enter length: "))
width = oat(input("Enter width: "))
print(f"Area: {calculate_area(shape, [length, width]):.2f}")
elif shape == "triangle":
base = oat(input("Enter base: "))
height = oat(input("Enter height: "))
print(f"Area: {calculate_area(shape, [base, height]):.2f}")
else:
print("Invalid shape")
2. Calculate simple interest

principal = oat(input("Enter principal amount: "))


rate = oat(input("Enter rate of interest (%): "))
time = oat(input("Enter time period (years): "))

simple_interest = (principal * rate * time) / 100


print(f"Simple Interest: {simple_interest:.2f}")
3. Student records dictionary

student_records = {}

def add_student():
id = input("Enter student ID: ")
name = input("Enter student name: ")
grades = input("Enter grades (comma-separated): ")
attendance = input("Enter attendance percentage: ")
student_records[id] = {"name": name, "grades": grades, "attendance":
attendance}
fl
fl
fl
fl
fl
fl
fl
fl
fi
def update_student():
id = input("Enter student ID to update: ")
if id in student_records:
eld = input("Enter eld to update (name/grades/attendance): ")
value = input(f"Enter new { eld}: ")
student_records[id][ eld] = value
else:
print("Student not found")

def display_records():
for id, info in student_records.items():
print(f"ID: {id}, Name: {info['name']}, Grades: {info['grades']},
Attendance: {info['attendance']}")

while True:
choice = input("\n1. Add Student\n2. Update Record\n3. Display
Records\n4. Exit\nChoice: ")
if choice == '1':
add_student()
elif choice == '2':
update_student()
elif choice == '3':
display_records()
elif choice == '4':
break
else:
print("Invalid choice")
4. Check if number is even or odd

def check_even_odd(num):
return "Even" if num % 2 == 0 else "Odd"

number = int(input("Enter a number: "))


print(f"{number} is {check_even_odd(number)}")
5. Check if number is prime

def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i=5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
fi
fi
fi
fi
return True

num = int(input("Enter a number: "))


print(f"{num} is {'prime' if is_prime(num) else 'not prime'}")
6. Generate multiplication table

number = int(input("Enter a number: "))


for i in range(1, 11):
print(f"{number} × {i} = {number * i}")
7. Simple calculator

def calculate(a, b, operation):


if operation == '+':
return a + b
elif operation == '-':
return a - b
elif operation == '*':
return a * b
elif operation == '/':
return a / b if b != 0 else "Error: Division by zero"
else:
return "Invalid operation"

num1 = oat(input("Enter rst number: "))


num2 = oat(input("Enter second number: "))
op = input("Enter operation (+, -, *, /): ")
result = calculate(num1, num2, op)
print(f"Result: {result}")
8. Read text le and nd words of speci c lengths

def nd_words_by_length( lename, lengths):


words_by_length = {length: [] for length in lengths}
try:
with open( lename, 'r') as le:
for line in le:
for word in line.split():
word = word.strip('.,!?()"\'').lower()
if len(word) in lengths:
words_by_length[len(word)].append(word)
return words_by_length
except FileNotFoundError:
return "File not found"

lename = input("Enter lename: ")


lengths = [int(x) for x in input("Enter word lengths (comma-separated):
").split(',')]
results = nd_words_by_length( lename, lengths)
fi
fi
fl
fl
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
if isinstance(results, dict):
for length, words in results.items():
print(f"Words with {length} letters: {', '.join(words)}")
else:
print(results)
9. Division with exception handling

def safe_division(a, b):


try:
result = a / b
return result
except ZeroDivisionError:
return "Error: Cannot divide by zero"
except ValueError:
return "Error: Invalid input"

try:
num1 = oat(input("Enter rst number: "))
num2 = oat(input("Enter second number: "))
result = safe_division(num1, num2)
print(f"Result: {result}")
except ValueError:
print("Error: Please enter valid numbers")
10. Shopping cart system with classes

class Product:
def __init__(self, id, name, price, stock):
self.id = id
self.name = name
self.price = price
self.stock = stock

def update_stock(self, quantity):


if self.stock >= quantity:
self.stock -= quantity
return True
return False

class Customer:
def __init__(self, id, name):
self.id = id
self.name = name
self.orders = []

class ShoppingCart:
def __init__(self, customer):
self.customer = customer
self.items = {}
fl
fl
fi
self.total = 0.0

def add_item(self, product, quantity):


if product.update_stock(quantity):
if product.id in self.items:
self.items[product.id][1] += quantity
else:
self.items[product.id] = [product, quantity]
self.total += product.price * quantity
return True
return False

def checkout(self):
order = {"items": self.items.copy(), "total": self.total}
self.customer.orders.append(order)
self.items = {}
self.total = 0.0
return order

# Demo
products = [
Product(1, "Laptop", 1000, 5),
Product(2, "Mouse", 25, 20),
Product(3, "Keyboard", 50, 15)
]

customer = Customer(1, "John Doe")


cart = ShoppingCart(customer)

cart.add_item(products[0], 1)
cart.add_item(products[1], 2)
print(f"Cart total: ${cart.total}")

order = cart.checkout()
print(f"Order completed with total: ${order['total']}")

You might also like