Menu
Coddy logo textTech

הפקת דוח

חלק מהיחידה לוגיקה וזרימת תוכנית במסלול ה-Python של Coddy. שיעור 71 מתוך 78.

challenge icon

אתגר

קשה

למערכת המלאי כבר יש את הרכיבים הבאים:

  1. מילון גלובלי בשם inventory, שבו:
    • המפתחות הם שמות פריטים (מחרוזות)
    • הערכים הם מילונים המכילים:
      • "price": מחיר הפריט (מספר ממשי)
      • "stock": הכמות הנוכחית במלאי (מספר שלם)
  2. פונקציה בשם add_item(item, price, stock) שמוסיפה פריטים חדשים למלאי
  3. פונקציה בשם update_stock(item, quantity) שמעדכנת את רמת המלאי
  4. פונקציה בשם check_availability(item) שמחזירה את רמת המלאי הנוכחית

עליך לממש את הפונקציה sales_report(sales), אשר:

  1. מקבלת מילון sales, שבו:
    • המפתחות הם שמות פריטים
    • הערכים הם הכמויות שנמכרו
  2. עבור כל פריט במילון המכירות:
    • בודקת אם הפריט קיים במלאי
    • בודקת אם יש מספיק מלאי
    • מעדכנת את המלאי על ידי הפחתת הכמויות
    • מחשבת את ההכנסות על סמך המחיר והכמות שנמכרה
  3. מחזירה מחרוזת מעוצבת עם סך ההכנסות

טפל בשגיאות הספציפיות הבאות:

  • אם פריט לא קיים במלאי, הדפס: "Error: Item '{item}' not found."
  • אם אין מספיק מלאי, הדפס: "Error: Insufficient stock for '{item}'."

הפלט צריך להיות מחרוזת בפורמט: “Total revenue: ${total:.2f}”

 

הוסף (החלף) את קטע הקוד הבא בתחתית הקוד שלך:

add_item("Apple", 0.5, 50)
add_item("Banana", 0.2, 60)
sales = {"Apple": 30, "Banana": 20, "Orange": 10}  # Orange should print an error
print(sales_report(sales))  # Should output: Total revenue: $19.00
print(inventory)

נסו בעצמכם

inventory = {}

def add_item(item, price, stock):
    if item in inventory:
        print(f"Error: Item '{item}' already exists.")
        return
    try:
        inventory[item] = {"price": float(price), "stock": int(stock)}
        print(f"Item '{item}' added successfully.")
    except ValueError:
        print("Error: Price and stock must be numeric.")

def update_stock(item, quantity):
    if item not in inventory:
        print(f"Error: Item '{item}' not found.")
        return
    try:
        new_stock = inventory[item]["stock"] + int(quantity)
        if new_stock < 0:
            print(f"Error: Insufficient stock for '{item}'.")
        else:
            inventory[item]["stock"] = new_stock
            print(f"Stock for '{item}' updated successfully.")
    except ValueError:
        print("Error: Quantity must be an integer.")

def check_availability(item):
    if item not in inventory:
        return "Item not found"
    return inventory[item]["stock"]


add_item("Apple", 0.5, 100)
add_item("Banana", 0.2, 50)
update_stock("Apple", -20)
update_stock("Banana", 30)
print(check_availability("Apple"))  # Should return 80
print(check_availability("Banana"))  # Should return 80
print(check_availability("Orange"))  # Should return "Item not found"

כל השיעורים ביחידה לוגיקה וזרימת תוכנית

תרגלו בעצמכם: קומפיילר Python אונליין