0% found this document useful (0 votes)
23 views9 pages

Python Case Study: Ticket Pricing Logic

This document presents multiple real-world application case studies using Python, including a Shopping Cart Total Calculator, a BMI Calculator, a Movie Ticket Price Calculator, and an Inventory Management System. Each case study outlines a problem statement, provides solution code, and explains the use of variables, operators, and loops. Key takeaways emphasize the importance of data types, conditional logic, and iterative processes in practical programming scenarios.

Uploaded by

Amol Adhangale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views9 pages

Python Case Study: Ticket Pricing Logic

This document presents multiple real-world application case studies using Python, including a Shopping Cart Total Calculator, a BMI Calculator, a Movie Ticket Price Calculator, and an Inventory Management System. Each case study outlines a problem statement, provides solution code, and explains the use of variables, operators, and loops. Key takeaways emphasize the importance of data types, conditional logic, and iterative processes in practical programming scenarios.

Uploaded by

Amol Adhangale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

scenario based real world application case study on python variables with answers

Real-World Application Case Study: Shopping Cart Total Calculator


Problem Statement:
Create a Python program to calculate the total cost of items in a shopping cart,
including tax. The user will input item names, prices, and quantities. The program
will compute the subtotal, tax (8%), and total, then display a receipt.

Solution Code:
python
Copy
# Initialize variables
subtotal = 0.0
tax_rate = 0.08

print("Welcome to the Shopping Cart Calculator!")

while True:
item_name = input("\nEnter item name (or 'done' to finish): ")
if item_name.lower() == 'done':
break

item_price = float(input("Enter item price ($): "))


quantity = int(input("Enter quantity: "))

item_total = item_price * quantity


subtotal += item_total # Accumulate subtotal

tax_amount = subtotal * tax_rate


total = subtotal + tax_amount

# Display receipt
print("\n--- RECEIPT ---")
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax (8%): ${tax_amount:.2f}")
print(f"Total: ${total:.2f}")
Explanation:
Variables Used:

subtotal (float): Accumulates the total cost of all items before tax.

tax_rate (float): Stores the tax rate (8%).

item_name (str): Name of the item entered by the user.

item_price (float): Price of one unit of the item.

quantity (int): Number of units purchased.

item_total (float): Total cost for the item (price × quantity).

tax_amount (float): Calculated tax based on the subtotal.

total (float): Final amount to pay (subtotal + tax).

Key Steps:

A while loop repeatedly prompts the user for item details until they type "done".

Inputs for item_price and quantity are converted to float and int to perform
calculations.

The subtotal variable updates dynamically by adding each item_total.

Tax and total are computed after the loop exits.

Sample Input/Output:
Input:

Copy
Enter item name (or 'done' to finish): Apple
Enter item price ($): 0.99
Enter quantity: 3

Enter item name (or 'done' to finish): Bread


Enter item price ($): 2.50
Enter quantity: 2

Enter item name (or 'done' to finish): done


Output:

Copy
--- RECEIPT ---
Subtotal: $7.97
Tax (8%): $0.64
Total: $8.61
Key Takeaways:
Variable Types Matter: Using float for prices and int for quantities ensures
accurate arithmetic.

Type Conversion: Inputs from input() are strings and must be converted to numeric
types.

Accumulating Values: The subtotal variable demonstrates how to update a value


iteratively.

Real-World Relevance: This pattern is used in e-commerce platforms, POS systems,


and budgeting apps.

Exercise for Learners:


Modify the program to include a discount system:

If the subtotal exceeds $50, apply a 10% discount.

Update the receipt to show the discount amount and adjusted total.

Hint: Add variables like discount and discounted_subtotal to handle the new logic.

scenario based real world application case study on python variables with answers
Real-World Application Case Study: BMI (Body Mass Index) Calculator & Health
Category Classifier
Problem Statement:
Create a Python program that calculates a user’s BMI using their weight (kg) and
height (m). The program should classify the BMI into health categories
(Underweight, Normal, Overweight, Obese) using comparison and logical operators.
Display the BMI value and category.

Solution Code:
python
Copy
# Input variables
weight = float(input("Enter your weight in kilograms: "))
height = float(input("Enter your height in meters: "))

# Calculate BMI using arithmetic operators


bmi = weight / (height ** 2)

# Classify BMI using comparison and logical operators


category = ""
if bmi < 18.5:
category = "Underweight"
elif 18.5 <= bmi < 25:
category = "Normal"
elif 25 <= bmi < 30:
category = "Overweight"
else:
category = "Obese"

# Display results
print(f"\nBMI: {bmi:.1f}")
print(f"Category: {category}")
Explanation:
Operators Used:

Arithmetic Operators: Division (/), Exponentiation (**) for height squared.

Comparison Operators: <, <= for checking BMI ranges.

Logical Operators: Implicit and in chained comparisons (e.g., 18.5 <= bmi < 25).

Key Steps:

Convert user inputs for weight and height to float for precise calculations.

Calculate BMI using the formula: BMI = weight / (height²).

Use if-elif-else statements with comparison operators to classify the BMI into
health categories.

Format the BMI output to one decimal place for readability.

Sample Input/Output:
Input:

Copy
Enter your weight in kilograms: 70
Enter your height in meters: 1.75
Output:

Copy
BMI: 22.9
Category: Normal
Another Example:
Input:

Copy
Enter your weight in kilograms: 85
Enter your height in meters: 1.8
Output:

Copy
BMI: 26.2
Category: Overweight
Key Takeaways:
Arithmetic vs. Comparison Operators:

Arithmetic operators (/, **) handle mathematical computations.

Comparison operators (<, <=) evaluate conditions to classify data.

Chained Comparisons: Python allows 18.5 <= bmi < 25 instead of bmi >= 18.5 and bmi
< 25, simplifying code.

Real-World Relevance: BMI calculators are used in healthcare apps, fitness


trackers, and nutrition planning tools.

Exercise for Learners:


Modify the program to display the ideal weight range (corresponding to a BMI of
18.5–24.9) for the user’s height.
Hint: Use the formula weight = BMI * height² to calculate the minimum and maximum
ideal weight.
Example Output:

Copy
Ideal weight range for 1.75 m: 56.7 kg to 76.6 kg
This case study demonstrates how Python operators are essential for mathematical
computations, decision-making, and real-world health applications! 🏥

---

scenario based real world application case study on python conditional statement
with answers
### Real-World Application Case Study: Movie Ticket Price Calculator

#### **Problem Statement:**


Create a Python program that calculates the price of a movie ticket based on age,
student status, and membership. Use conditional statements to apply discounts and
display the final price.
- **Base Ticket Price**: $20
- **Discount Rules**:
- Children (age < 12): 50% off
- Seniors (age ≥ 65): 30% off
- Students: 25% off (requires verification)
- Membership: Additional 10% off (applied after other discounts)

---

#### **Solution Code:**

```python
base_price = 20.0
discount = 0.0

# Input user details


age = int(input("Enter your age: "))
is_student = input("Are you a student? (yes/no): ").lower() == "yes"
has_membership = input("Do you have a membership? (yes/no): ").lower() == "yes"
# Apply discounts based on conditions
if age < 12:
discount = 0.5
elif age >= 65:
discount = 0.3
elif is_student:
discount = 0.25

# Calculate final price


final_price = base_price * (1 - discount)

# Apply membership discount (if applicable)


if has_membership:
final_price *= 0.9 # Additional 10% off

# Display result
print(f"\nFinal Ticket Price: ${final_price:.2f}")
```

---

#### **Explanation:**

1. **Conditional Logic**:
- The program checks age first (`if age < 12`), then senior status (`elif age >=
65`), and finally student status (`elif is_student`).
- Membership discount is applied **after** other discounts using a separate `if`
statement.

2. **Variables**:
- `base_price`: Stores the base ticket price.
- `discount`: Holds the discount percentage based on age/student status.
- `final_price`: Computes the price after applying all discounts.

3. **Operator Use**:
- Comparison operators (`<`, `>=`) for age checks.
- Logical operators (implicit `and` in membership check).

---

#### **Sample Input/Output:**

**Input 1 (Child with Membership):**


```
Enter your age: 10
Are you a student? (yes/no): no
Do you have a membership? (yes/no): yes
```
**Output:**
```
Final Ticket Price: $9.00
```
*Explanation*: 50% child discount → $10. Membership adds 10% off → $9.

**Input 2 (Senior Student without Membership):**


```
Enter your age: 70
Are you a student? (yes/no): yes
Do you have a membership? (yes/no): no
```
**Output:**
```
Final Ticket Price: $14.00
```
*Explanation*: Senior discount (30%) overrides student discount.

---

#### **Key Takeaways:**


1. **Order of Conditions Matters**: Child/senior discounts are prioritized over
student status.
2. **Membership as a Bonus Discount**: Applied after other discounts using
multiplication.
3. **Real-World Use**: Similar logic is used in e-commerce, event booking systems,
and loyalty programs.

---

#### **Exercise for Learners:**


Modify the program to include **group discounts**:
- If the user buys 4+ tickets, apply a 15% group discount (before membership
discount).
- Example Input: `Number of tickets: 5` → Group discount → Final price updates.

**Sample Output:**
```
Final Ticket Price: $12.92
```
*Hint*: Add a `ticket_quantity` variable and adjust the logic for group discounts!

---

This case study demonstrates how Python’s conditional statements enable dynamic
pricing logic in real-world applications! 🎬

scenario based real world application case study on python loops with answers
### Scenario-Based Real World Application Case Study: Python Loops

#### Scenario: Inventory Management System for a Retail Store

**Background:**
A retail store wants to automate its inventory management system using Python. The
store has a list of products, each with a name, quantity, and price. The store
needs to perform the following tasks:
1. Display all products.
2. Check for low stock (products with quantity less than 10).
3. Calculate the total value of the inventory.
4. Restock products that are low in stock.
5. Remove products that are out of stock.

**Data:**
```python
inventory = [
{"name": "Apple", "quantity": 15, "price": 0.50},
{"name": "Banana", "quantity": 5, "price": 0.25},
{"name": "Orange", "quantity": 8, "price": 0.75},
{"name": "Mango", "quantity": 0, "price": 1.50},
{"name": "Grapes", "quantity": 12, "price": 2.00},
]
```

---

### Tasks and Solutions Using Python Loops

#### Task 1: Display All Products


**Objective:** Print the details of all products in the inventory.

**Solution:**
```python
def display_products(inventory):
print("Product Inventory:")
for product in inventory:
print(f"Name: {product['name']}, Quantity: {product['quantity']}, Price: $
{product['price']:.2f}")

display_products(inventory)
```

**Output:**
```
Product Inventory:
Name: Apple, Quantity: 15, Price: $0.50
Name: Banana, Quantity: 5, Price: $0.25
Name: Orange, Quantity: 8, Price: $0.75
Name: Mango, Quantity: 0, Price: $1.50
Name: Grapes, Quantity: 12, Price: $2.00
```

---

#### Task 2: Check for Low Stock


**Objective:** Identify and display products with a quantity less than 10.

**Solution:**
```python
def check_low_stock(inventory):
print("Low Stock Products:")
for product in inventory:
if product['quantity'] < 10:
print(f"Name: {product['name']}, Quantity: {product['quantity']}")

check_low_stock(inventory)
```

**Output:**
```
Low Stock Products:
Name: Banana, Quantity: 5
Name: Orange, Quantity: 8
Name: Mango, Quantity: 0
```

---

#### Task 3: Calculate Total Inventory Value


**Objective:** Calculate the total value of the inventory (sum of quantity * price
for all products).

**Solution:**
```python
def calculate_total_value(inventory):
total_value = 0
for product in inventory:
total_value += product['quantity'] * product['price']
return total_value

total_value = calculate_total_value(inventory)
print(f"Total Inventory Value: ${total_value:.2f}")
```

**Output:**
```
Total Inventory Value: $34.75
```

---

#### Task 4: Restock Low Stock Products


**Objective:** Restock products with a quantity less than 10 by adding 20 units to
their quantity.

**Solution:**
```python
def restock_low_products(inventory):
for product in inventory:
if product['quantity'] < 10:
product['quantity'] += 20
print(f"Restocked {product['name']}. New Quantity:
{product['quantity']}")

restock_low_products(inventory)
```

**Output:**
```
Restocked Banana. New Quantity: 25
Restocked Orange. New Quantity: 28
Restocked Mango. New Quantity: 20
```

---

#### Task 5: Remove Out-of-Stock Products


**Objective:** Remove products with a quantity of 0 from the inventory.

**Solution:**
```python
def remove_out_of_stock(inventory):
inventory[:] = [product for product in inventory if product['quantity'] > 0]
print("Updated Inventory After Removing Out-of-Stock Products:")
display_products(inventory)

remove_out_of_stock(inventory)
```
**Output:**
```
Updated Inventory After Removing Out-of-Stock Products:
Product Inventory:
Name: Apple, Quantity: 15, Price: $0.50
Name: Banana, Quantity: 25, Price: $0.25
Name: Orange, Quantity: 28, Price: $0.75
Name: Grapes, Quantity: 12, Price: $2.00
```

---

### Summary
This case study demonstrates how Python loops (`for` and `if` statements) can be
used to solve real-world problems like inventory management. By iterating through
the inventory list, we can perform tasks such as displaying products, checking
stock levels, calculating total value, restocking, and removing out-of-stock items.
These techniques are scalable and can be adapted to more complex scenarios.

Common questions

Powered by AI

In the restocking process, loops are used to iterate through each product in the inventory to check the stock level of each item. For products with a quantity less than 10, the loop updates the inventory by adding 20 units to replenish stock . This looping mechanism allows the system to automatically identify low stock items and update their quantities in bulk, ensuring efficient management of stock levels without manual intervention.

Formatted strings enhance the Shopping Cart Total Calculator program by providing clear and precise output. By using formatted strings like `f"{variable:.2f}"`, the program can display numbers with a fixed number of decimal places, improving readability and professionalism in the output. This is particularly important in a financial context, where precision is critical. Formatting ensures that numeric values are presented consistently, making the receipt more user-friendly and minimizing misunderstandings regarding prices, subtotals, and totals, thus embedding consumer trust in the transaction process .

Arithmetic operators, specifically division and exponentiation, are used to calculate the BMI value using the formula BMI = weight / (height ** 2). Comparison operators are then used to classify the computed BMI into categories such as Underweight, Normal, Overweight, and Obese. The if-elif-else structure, with conditions using operators like `<` and `<=`, checks these ranges to assign the correct health category to the BMI . These two types of operators work together to first derive a numerical value and then to interpret it into a meaningful classification.

Python's `for` loop can effectively manage a list-based inventory system by iterating over each product's data to perform routine checks and updates. Tasks like displaying item details, calculating total value, verifying stock levels, restocking, and removing inactive items can be automated. For example, a `for` loop allows checking each product's quantity to determine low stock items efficiently, then using conditional logic to update quantities. The benefit is an automated, scalable approach that simplifies inventory management, reduces human error, enhances operational efficiency, and improves the timing for restocking, contributing to a more responsive retail environment .

`If` conditions for checking low stock in inventory management systems are crucial for identifying products in need of restocking. These conditions inspect each product's quantity, retrieving only those below the set threshold (less than 10 in this case). This logic helps in decisions about replenishing inventory efficiently without external assessment. Interaction with programming logic occurs by filtering the inventory list through conditional checks within loops, automatically triggering restock protocols for identified products and ensuring continuous stock readiness for customer satisfaction and sales optimization .

A subtotal discount system can be integrated into the Shopping Cart Total Calculator by adding conditional logic to check if the accumulated subtotal exceeds a certain threshold—such as $50—and apply a discount if true. New variables like `discount_rate` and `discount_amount` should be introduced to manage the discount calculation. Before computing the tax, the calculator can subtract the discount amount from the subtotal, ensuring the discount affects only pre-tax values. The receipt should be updated to show the discount amount, adjusted subtotal, and total after tax. This extension requires careful placement of calculations to maintain accuracy and clarity in the output .

Applying membership discounts at the last stage in the movie ticket price program is a strategic decision to maximize customer savings by applying the highest percentage discount to the already reduced price. This approach benefits customers and can act as an incentive for more users to opt into the membership program. It reflects a typical business logic where loyalty rewards are applied on top of other promotional discounts, increasing customer satisfaction. The impact is that members effectively receive a higher total discount, encouraging customer loyalty and engagement, but it could also reduce immediate revenue per ticket if not balanced with overall sales volume considerations .

Type conversion is critical in the Shopping Cart Total Calculator to ensure that arithmetic operations can be performed correctly on input data. User inputs for item price and quantity are initially received as strings from the `input()` function, which need to be converted into appropriate numeric types: `float` for prices and `int` for quantities. Without this conversion, mathematical calculations like total cost and tax computation cannot be accurately performed .

Without input validation, handling string inputs from users in a BMI calculator can lead to incorrect calculations, program crashes, or unexpected behavior. For instance, if a user enters a non-numeric string, the conversion to a float will raise a ValueError, interrupting the execution. Additionally, negative or zero values for weight and height, though syntactically correct as numbers, will lead to logical errors since they are invalid in calculating BMI. Lack of validation could also lead to unrealistic BMI classifications, damaging the program’s reliability and user trust . Proper validation guards against such issues by ensuring inputs meet expected criteria before further processing.

The implementation of discount logic in the movie ticket price calculator can be improved by using functions or a configuration-driven approach to make it more clear and extensible. Each discount type (e.g., child, senior, student, membership) can be encapsulated in separate functions that handle the respective conditions and calculations. Additionally, using a configuration dictionary to store discount rates and the order of application can separate logic from data, thus enhancing clarity and making it easier to update or extend the logic without modifying the core computational code. This minimizes hardcoding of discount values and conditions, centralizing them for better management.

You might also like