Thursday, November 9, 2017

First Classes

#First class example
#dice

from random import randrange

class die:
    def __init__(self, sides):
        self.sides=sides
        self.value=1

    def roll(self):
        self.value=randrange(1,self.sides+1)

    def getValue(self):
        return self.value

    def setValue(self, value):
        self.value=value


def main():
    again="y"
    num=int(input("How many sides "))
    while again=="y":
    
        die1=die(num)
        die1.roll()
        die2=die(num)
        die2.roll()
        print (die1.getValue(),die2.getValue())
        again=input("Enter y to roll again ")

main()
                            
    
    

Two classes

#item and sale and receipt

class item:
    def __init__(self, name, price):
        self.name=name
        self.price=price
        
    def getName(self):
        return self.name

    def getPrice(self):
        return self.price
    

class cart:
    def __init__(self):
        self.items=[]
        
    def addItem(self, product):
        self.items.append(product)

    def getTotal(self):
        total=0
        for i in self.items:
            total+=i.price
        return total

def main():
    more = "y"
    c=cart()
    while more=="y":
        name = input("Item Name ")
        price = float(input("Item Price "))
        product=item(name, price)
        c.addItem(product)
        more = input("y to continue")
    print (c.getTotal())

main()
        
            
        
            
        

No comments:

Post a Comment