- Home
- Course Detail
regularpython@gmail.com
You are now watching:
Python Basics in English / of Basics Introduction
Python: Price Calculation — Side-by-Side Patterns
Basic Structure
Theory:
- All logic is written inline. Great for quick demos but hard to reuse or test.
- Variables hold data; operations (like
*) compute results;printshows output. - Use this when you want the simplest possible example with minimal structure.
book_price = 20 quantity = 2 total = book_price * quantity print('Total Amount: ', total)
Function based design
Theory:
- Encapsulates logic inside a function for reuse and testing.
- Inputs become parameters (
book_price,quantity); output can be returned or printed. - Use this when there is one clear operation and you want to call it multiple times.
def calculate_product_price(book_price, quantity): total = book_price * quantity print('Total Amount: ', total) calculate_product_price(20, 3)
Class based design
Theory:
- Object-oriented: bundle data (
name) and behavior (calulate_price,display_details). - Great when you have multiple related operations for the same entity (Product).
- Scale with more methods (discounts, taxes) and maintain state within objects.
class Product: def __init__(self): self.name = "Sairam" def calulate_price(self, book_price, quantity): total = book_price * quantity print('Total Amount: ', total, self.name) def display_details(self): print("Product name", self.name) obj = Product() obj.calulate_price(20, 3) obj.display_details()
Production Code
Theory:
- Adds
loggingfor observability: info for business flow, debug for troubleshooting. - Type hints (
float,int,None) communicate intent and work with linters. - Suitable for real projects where auditability and maintainability matter.
import logging # Configure logging logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) class Product: def __init__(self, name: str): self.name: str = name logging.info(f"Product initialized with name: {self.name}") def calculate_price(self, book_price: float, quantity: int) -> float: logging.info(f"Calculating price for {self.name}") logging.debug(f"Book Price: {book_price}, Quantity: {quantity}") total: float = book_price * quantity logging.info(f"Total Amount: {total} for {self.name}") return total def display_details(self) -> None: logging.info(f"Displaying product details for {self.name}") logging.info(f"Product Name: {self.name}") # Example usage if __name__ == "__main__": obj = Product(name="Sairam") obj.calculate_price(book_price=20, quantity=2) obj.display_details()