Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Customize Truthiness with __bool__

Learn how to control an object's truth value by implementing __bool__ so instances behave naturally in boolean contexts.

Python practice15 minMagic Methods & Operator OverloadingIntermediateLast updated April 11, 2026

Problem statement

Implement the ShoppingCart class so that Python's bool() applied to an instance returns True when the cart contains at least one item with a positive quantity, and False otherwise. Items are represented as (name, quantity) pairs stored in a list. Your implementation should be robust to numeric quantities (ints or floats) and treat non-numeric quantities as zero.

Task

Implement a ShoppingCart class whose boolean truthiness reflects whether the cart contains any positive quantity items.

Examples

Non-empty cart is truthy

Input

bool(ShoppingCart([('apple', 2)]))

Output

True

The cart has a single item with quantity 2, so the cart is truthy.

Input format

A single expression will be evaluated. For tests, bool() will be called on ShoppingCart instances constructed with a list of (name, quantity) tuples.

Output format

The expression should evaluate to a Python value whose string form is compared to the expected output.

Constraints

Quantities are expected to be non-negative numbers (int or float). Non-numeric quantities should be treated as zero. The __bool__ method must return a boolean.

Samples

Sample 1

Input

bool(ShoppingCart([('banana', 0), ('pear', 1.5)]))

Output

True

One item has a positive quantity (1.5), so the cart is truthy.