לדלג לתוכן

9.2 פונקציות ומחלקות תרגול

ניקוי קוד - פונקציות

  • הקוד הבא מפר מספר עקרונות של קוד נקי שלמדנו. מצאו את כל הבעיות ותקנו אותן.
    def handle_order(customer_name, customer_email, product_id, product_name, quantity, price_per_unit, discount_percent, shipping_address, shipping_city, shipping_country):
        total = quantity * price_per_unit
        discounted = total - (total * discount_percent / 100)
        print(f"Order for {customer_name}")
        print(f"Email: {customer_email}")
        print(f"Product: {product_name} x{quantity}")
        if discount_percent > 0:
            print(f"Discount: {discount_percent}%")
        print(f"Total: {discounted}")
        import smtplib
        # send confirmation email
        print(f"Confirmation sent to {customer_email}")
        db = {}
        db[customer_email] = {"product": product_id, "qty": quantity}
        print("Order saved to database")
    
  • אילו עקרונות הופרו? רשמו אותם לפני שאתם מתחילים לתקן.

ניקוי קוד - רמות אבסטרקציה

  • הקוד הבא מערבב רמות אבסטרקציה שונות בפונקציה אחת. ארגנו מחדש:
    def generate_report(data):
        valid = []
        for item in data:
            if isinstance(item, dict) and "score" in item and item["score"] >= 0:
                valid.append(item)
    
        total = sum(item["score"] for item in valid)
        avg = total / len(valid) if valid else 0
    
        print("=" * 40)
        print("REPORT")
        print("=" * 40)
        print(f"Total entries: {len(valid)}")
        print(f"Average score: {avg:.2f}")
        top = sorted(valid, key=lambda x: x["score"], reverse=True)[:3]
        for i, entry in enumerate(top, 1):
            print(f"{i}. {entry.get('name', 'Unknown')} - {entry['score']}")
    

בונוס - ערכים קסומים

  • מצאו את כל ה"מספרי הקסם" בקוד הבא והוציאו אותם לקבועים עם שמות ברורים:
    def calculate_shipping(weight, distance):
        if weight > 30:
            base = weight * 4.5
        else:
            base = weight * 2.8
    
        if distance > 500:
            base *= 1.35
    
        if base < 15:
            base = 15
    
        return round(base, 2)