Python Fundamentals – Practical Exercise 2: Building a Shopping Cart Total Calculator
1. Introduction
Welcome to the second practical exercise in our Python Fundamentals series!
In our previous exercise, we developed a Class Grades Summary Calculator using functions, lists, loops, and conditional statements.
This time, we'll apply these concepts to a different real-world scenario: building a Shopping Cart Total Calculator.
Our program will collect information about items being purchased, calculate the total price based on their quantities, apply discounts when applicable, and generate a summary of the shopping cart.
The objective is to understand how Python functions, loops, lists, and conditional logic can work together to solve a practical programming problem.
2. Exercise Requirements
We need to develop a program that performs the following tasks:
Ask the user for the number of items they want to purchase.
For each item:
Ask for the item's name.
Ask for its price.
Ask for the desired quantity.
Create two functions:
Calculate the total price of an item.
Apply a 10% discount if the item's total is greater than or equal to 100.
Use a
forloop to calculate the discounted total for each item.Store each item's name, quantity, and discounted total in a list.
Display a formatted shopping cart summary.
Calculate and display the grand total.
Discount Rules
| Item Total | Discount |
|---|---|
| Below 100 | No discount |
| 100 or above | 10% discount |
For this exercise, the discount is applied individually to each item's total, rather than to the entire shopping cart.
3. Understanding the Program Structure
Before implementing the solution, let's divide the program into smaller components.
Function 1 – calculate_item_total()
Receives the item's price and quantity, then calculates the total before discount.
Function 2 – apply_discount()
Receives the calculated item total and checks whether it qualifies for a 10% discount.
Main Program
Collects the shopping information and stores each item's name, price, and quantity.
Results Processing
Uses a for loop to calculate the final price of every item after applying the appropriate discount.
Shopping Cart Summary
Displays each item, its quantity, its discounted total, and the overall grand total.
4. Complete Python Solution
Here is the complete implementation:
# Function to calculate the total price of an item
def calculate_item_total(price, quantity):
return price * quantity
# Function to apply a 10% discount if the total is >= 100
def apply_discount(total):
if total >= 100:
return round(total * 0.90, 2)
else:
return round(total, 2)
# Main program
# Ask for the number of items
num_items = int(input("Enter the number of items to buy: "))
# Store the original item information
items = []
# Collect information for each item
for i in range(num_items):
print(f"\nItem {i + 1}")
name = input("Enter item name: ")
price = float(input("Enter item price: "))
quantity = int(input("Enter quantity: "))
# Store item information
items.append((name, price, quantity))
# Store the final shopping cart results
results = []
# Calculate discounted totals and grand total
grand_total = 0
for name, price, quantity in items:
# Calculate item total before discount
total = calculate_item_total(price, quantity)
# Apply discount where applicable
discounted_total = apply_discount(total)
# Store item name, quantity, and discounted total
results.append((name, quantity, discounted_total))
# Add discounted total to grand total
grand_total += discounted_total
# Display shopping cart summary
print("\n========== SHOPPING CART SUMMARY ==========")
print(f"{'Item Name':<20}{'Quantity':>10}{'Total':>12}")
print("-" * 42)
for name, quantity, total in results:
print(f"{name:<20}{quantity:>10}{total:>12.2f}")
print("-" * 42)
print(f"{'Grand Total':<30}{grand_total:>12.2f}")
print("=" * 42)5. Understanding the Code
Let's examine the main components of our program.
5.1 Calculating the Item Total
def calculate_item_total(price, quantity):
return price * quantityThis function receives two parameters:
price: The price of one item.quantity: The number of units being purchased.
It multiplies both values and returns the result.
For example:
total = calculate_item_total(25, 4)
print(total)Output:
100The total price is 100 because four items cost 25 each.
5.2 Applying the Discount
def apply_discount(total):
if total >= 100:
return round(total * 0.90, 2)
else:
return round(total, 2)This function uses an if/else conditional statement to determine whether an item qualifies for a discount.
The condition is:
total >= 100If the item total is 100 or greater, we multiply it by 0.90.
Why 0.90?
Because applying a 10% discount means the customer pays 90% of the original price.
For example:
print(apply_discount(100))
print(apply_discount(80))Output:
90.0
80.0The first item receives a 10% discount, while the second item remains unchanged.
The round() function limits the returned monetary amount to two decimal places for display and storage in this exercise.
5.3 Collecting Shopping Information
num_items = int(input("Enter the number of items to buy: "))
items = []We first ask the user how many items they want to purchase.
We then create an empty list called items.
This list will store the original information for every item.
5.4 Collecting Item Details Using a For Loop
for i in range(num_items):
print(f"\nItem {i + 1}")
name = input("Enter item name: ")
price = float(input("Enter item price: "))
quantity = int(input("Enter quantity: "))
items.append((name, price, quantity))The for loop repeats according to the number of items entered by the user.
For every item, the program collects:
Name.
Price.
Quantity.
We use append() to store these values as a tuple inside the items list.
For example:
items = [
("Laptop", 120.00, 1),
("Headphones", 40.00, 2),
("Keyboard", 55.00, 2)
]At this stage, we have collected all the information needed to calculate the shopping cart totals.
5.5 Processing Items and Applying Discounts
results = []
grand_total = 0
for name, price, quantity in items:
total = calculate_item_total(price, quantity)
discounted_total = apply_discount(total)
results.append((name, quantity, discounted_total))
grand_total += discounted_totalThis is the main calculation stage of our program.
We iterate through the items list and calculate each item's total price.
The calculate_item_total() function calculates the original total, while apply_discount() determines the final amount after the discount.
We then store the following information in the results list:
Item name.
Quantity.
Total after discount.
Finally, we use:
grand_total += discounted_totalThis adds each item's discounted total to the overall shopping cart total.
5.6 Displaying the Shopping Cart Summary
print(f"{'Item Name':<20}{'Quantity':>10}{'Total':>12}")
print("-" * 42)
for name, quantity, total in results:
print(f"{name:<20}{quantity:>10}{total:>12.2f}")We use f-string formatting to organize the output into columns.
<20aligns the item name to the left.>10aligns the quantity to the right.>12.2faligns the total to the right and displays two decimal places.
After displaying all items, we print the grand total.
6. Example Execution
Let's test our program with three items.
User Input:
Enter the number of items to buy: 3
Item 1
Enter item name: Laptop
Enter item price: 120
Enter quantity: 1
Item 2
Enter item name: Headphones
Enter item price: 40
Enter quantity: 2
Item 3
Enter item name: Keyboard
Enter item price: 55
Enter quantity: 2Program Output:
========== SHOPPING CART SUMMARY ==========
Item Name Quantity Total
------------------------------------------
Laptop 1 108.00
Headphones 2 80.00
Keyboard 2 99.00
------------------------------------------
Grand Total 287.00
==========================================6.1 Understanding the Calculations
Let's verify the results.
Laptop
Unit price: 120
Quantity: 1
Original total: 120
Discount: 10%
Final total: 108
Headphones
Unit price: 40
Quantity: 2
Original total: 80
Discount: None
Final total: 80
Keyboard
Unit price: 55
Quantity: 2
Original total: 110
Discount: 10%
Final total: 99
The grand total is calculated by adding the discounted totals:
108 + 80 + 99 = 287.
7. Python Concepts Applied
This exercise combines several concepts introduced throughout our Python Fundamentals tutorials.
| Python Concept | How We Used It |
|---|---|
| Functions | Calculate item totals and apply discounts. |
| Function Parameters | Pass prices, quantities, and totals into functions. |
| Lists | Store shopping cart information and results. |
| Tuples | Group each item's information. |
| For Loops | Iterate through items and calculate prices. |
| Input | Collect item names, prices, and quantities. |
| Type Casting | Convert user input into integers and floats. |
| Conditional Statements | Determine whether an item qualifies for a discount. |
| List Methods | Use append() to store item information. |
| Built-in Functions | Use round() for monetary values. |
| F-Strings | Format the shopping cart summary. |
| Accumulator | Calculate the grand total using +=. |
8. Conclusion
Congratulations! You've completed the second practical programming exercise in the Python Fundamentals series.
In this exercise, we developed a shopping cart calculator that collects item information, calculates individual totals, applies conditional discounts, and produces a final shopping cart summary.
The main takeaway is learning how to combine functions and loops with conditional logic to solve a practical problem.
We also reinforced how lists and tuples can be used to organize information and how accumulator variables can help calculate running totals.
These programming techniques are useful in many applications, including inventory systems, financial calculations, e-commerce platforms, and automated reporting.
Keep practicing, experiment with the code, and try modifying the discount rules to explore different outcomes.
Comments