Ex 21: Order Invoice Generator
Problem
Build an automated restaurant invoice system that generates a detailed report for customers.
Rules
- Define
generate_invoice(customer_name="Guest", *items, **charges) -> str. *itemsaccepts any number of positional arguments for food items.**chargesaccepts any number of keyword arguments for costs liketaxorservice.- Sum only the values from
**chargesfor the total amount.
Boilerplate
Copy below code and paste to our IDE for head start.
# Write our code inside this function
def generate_invoice(customer_name="Guest", *items, **charges):
pass # remove this
# Call with test data
print(generate_invoice("Amit", "Burger", "Fries", tax=50.0, service=20.0))
Expected Output
Invoice for Amit:
Items:
- Burger
- Fries
Charges:
Tax: 50.0
Service: 20.0
Total Amount Due: ₹70.0
Solution
Only view the solution after trying our best.
Show solution
def generate_invoice(customer_name: str = "Guest", *items: str, **charges: float) -> str:
lines = [f"Invoice for {customer_name}:"]
if items:
lines.append("Items:")
for item in items:
lines.append(f"- {item}")
if charges:
lines.append("Charges:")
for name, amount in charges.items():
lines.append(f"{name.capitalize()}: {amount}")
total = sum(charges.values())
lines.append(f"Total Amount Due: ₹{total}")
return "\n".join(lines)
# Test data
print(generate_invoice("Amit", "Burger", "Fries", tax=50.0, service=20.0))
Details
Using *args and **kwargs provides maximum flexibility for our functions. Positional arguments (*items) are collected into a tuple, while keyword arguments (**charges) are collected into a dictionary, which makes calculating the total with sum(charges.values()) very straightforward.