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

pythonchpscenario

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
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

pythonchpscenario

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
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

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.

You might also like