Benutzer:MovGP0/Python/Loops

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      

nums = [1,2,3,4,5]

# foreach
for n in nums:
    print(n, end=', ')

# for
# enumerate makes the (value) list into an (index, value) tuple list
for index, n in enumerate(nums)
    print(n, end=', ')

class CartItem:
    def __init__(self, name, price):
        self.price = price
        self.name = name

    def __repr__(self):
        return "({0}, ${1})".format(self.name, self.price)

class ShoppingCart: 
    # ctor
    def __init__(self): 
        self.__items = [] # '__name' means private

    def add(self, cart_item):
        self.__items.append(cart_item)

    # IEnumerable.GetEnumerator()
    def __iter__(self): 
        return self.__items.__iter__()

    # property decorator
    # implements as getter instead of method
    @property
    def total_price(self)
        for item in self.__items:
            total += item.price
        return total


# var cart = new ShoppingCart();
cart = ShoppingCart()
cart.add(CartItem("CD", 19.99))
cart.add(CartItem("Record", 17.99))

for item in cart.items: 
    print(item)

print("Total price is ${0:,}".format(cart.total_price))