Difference between revisions of "CSC111 Programs for Week 9 2015"

From dftwiki3
Jump to: navigation, search
(Cats)
Line 60: Line 60:
 
<br />
 
<br />
 
::<source lang="python">
 
::<source lang="python">
 
 
# cats1.py
 
# cats1.py
 
# D. Thiebaut
 
# D. Thiebaut
# Program for Week #9
+
# program developed in class on 4/1/15
# Define a Cat class, and
+
#
# use it to create a collection of
 
# cats.
 
 
 
 
 
 
class Cat:
 
class Cat:
     """a class that implements a cat and its
+
     """Cat class.  contains information about a cat: name,
     information.  Name, breed, vaccinated,
+
     whether vaccinated, breed, and age"""
    tattooed, and age."""
+
     def __init__( self, na, vacc, bree, ag ):
 
 
     def __init__( self, na, brd, vacc, ag ):
 
        """constructor.  Builds a cat with all its information"""
 
 
         self.name      = na
 
         self.name      = na
        self.breed      = brd
 
 
         self.vaccinated = vacc
 
         self.vaccinated = vacc
 +
        self.breed      = bree
 
         self.age        = ag
 
         self.age        = ag
 +
 +
    def __str__( self ):
 +
        """default string representation for a cat.  Will be use by print() if
 +
        we ask it to print a cat object."""
 +
        if self.vaccinated:
 +
            vac = "vaccinated"
 +
        else:
 +
            vac = "not vaccinated"
 +
        # create the string representation of the object
 +
        s = "{0:10} ==> ({1:1}), {2:1}, {3:1}".format(
 +
            self.name, self.breed, self.age, vac )
 +
 +
        # return the string representation
 +
        return s
 +
   
 +
    def getName( self ):
 +
        """returns the name of the cat"""
 +
        return self.name
  
 
     def isVaccinated( self ):
 
     def isVaccinated( self ):
         """returns True if cat is vaccinated, False otherwise"""
+
         """returns True if the cat is vaccinated, False otherwise."""
 +
        #if self.vaccinated:
 +
        #    return True
 +
        #else:
 +
        #    return False
 
         return self.vaccinated
 
         return self.vaccinated
  
    def getAge( self ):
+
# -------------------------------------------------------------
        """returns cat's age"""
+
#                          MAIN
         return self.age
+
# -------------------------------------------------------------
 +
 
 +
def main():
 +
    # create an empty list of cats
 +
    catList = []
 +
 
 +
    # Create 3 cat objects and add them to the list
 +
    # Minou, 3, vaccinated, stray
 +
    #catList.append( Cat( "Minou", True, "stray", 3 ) )
 +
    #catList.append( Cat( "Ralph", False, "Burmese", 1 ) )
 +
    #catList.append( Cat( "Garfield", True, "Orange Tabby", 10 ) )
 +
 
 +
    # open csv file containing cats.  Example of line in file shown below.
 +
    # Winston, 1, not vaccinated,  stray
 +
    file = open( "cats.csv", "r" )
 +
    lines = file.readlines()
 +
    file.close()
 +
 
 +
    # the contents of the file is now in a list of strings.  The list is called lines.
 +
 
 +
    # for each line in the list of lines...
 +
    for line in lines:
 +
         #print( line )
 +
 
 +
        # split the line into 4 fields
 +
        fields = line.split( ',' )
  
    def getName( self ):
+
        # if the line doesn't contain 4 fields, it must be invalid.  Skip it!
         """return name of cat"""
+
        if len( fields ) != 4:
         return self.name
+
            continue
 +
 
 +
         # assign each one of the 4 items in the list fields to 4 different variables
 +
        name, age, vacc, breed = fields
 +
 
 +
        # transform vacc from "vaccinated" or "not vaccinated" to True or False
 +
        if vacc.lower().strip() == "vaccinated":
 +
            vacc = True
 +
         else:
 +
            vacc = False
  
    def __str__( self ):
+
         # add a new cat with this information to the list of cats
         """default string representation of cat"""
+
         cat = Cat( name.strip(), vacc, breed.strip(), int(age.strip()) )
         vacc = "vaccinated"
+
         catList.append( cat ) 
         if not self.vaccinated:
 
            vacc = "not vaccinated"
 
 
          
 
          
        return "{0:20}:==> {1:1}, {2:1}, {3:1} yrs old".format(
+
     # list all the cats in the list
            self.name, self.breed, vacc, self.age )
+
     for cat in catList:
      
 
def main():
 
    """ main program.  Creates a list of cats and displays
 
    groups sharing the same property.
 
        Minou, 3, vac, stray
 
        Max, 1, not-vac, Burmese
 
        Gizmo, 2, vac, Bengal
 
        Garfield, 4, not-vac, Orange Tabby
 
    """
 
    cats = []
 
    cat = Cat( "Minou", "stray", True, 3 )
 
    cats.append( cat )
 
   
 
    cats.append( Cat( "Max", "Burmese", False, 1 ) )
 
    cats.append( Cat( "Gizmo", "Bengal", True, 2 ) )
 
    cats.append( Cat( "Garfield", "Orange Tabby", False, 4 ) )
 
 
 
    # print the list of all the cats
 
    print( "\nComplete List:" )
 
     for cat in cats:
 
 
         print( cat )
 
         print( cat )
  
    # print only the vaccinated cats
 
    print( "\nVaccinated cats:" )
 
    for cat in cats:
 
        if cat.isVaccinated()==True:
 
            print( cat )
 
 
    # print cats older than 2
 
    print( "\nCats 2 or older:" )
 
    for cat in cats:
 
        if cat.getAge()>=2:
 
            print( cat )
 
  
 +
   
 +
main()
  
if __name__=="__main__":
 
    main()
 
  
 
      
 
      

Revision as of 11:44, 1 April 2015

--D. Thiebaut (talk) 09:03, 30 March 2015 (EDT)


Die


# dice.py
# D. Thiebaut
# Program for Week 9
# an example program that defines a Die class, and
# demonstrates how to create 2 objects from this class.

import random


class Die:
    """a class implementing a Die, with a given number
    of sides, and a value (the number of the top face)"""
    
    def __init__( self, n ):
        """initializes the die with n faces, and a value 1,
        by default"""
        self.noSides = n
        self.value   = 1

    def roll( self ):
        """roll the die and pick a new random value for it"""
        self.value = random.randrange( 1, self.noSides+1 )

    def getValue( self ):
        """return the current value, i.e. the number on the top
        side"""
        return self.value


def main():
    # Create 2 dice, one with 6 sides, one with 8
    d1 = Die( 6 )
    d2 = Die( 8 )

    while True:
        # Roll both dice
        d1.roll( )
        d2.roll( )

        # display their value
        print( "Die 1: ",  d1.getValue() )
        print( "Die 2: ",  d2.getValue() )

        ans = input( "Press enter to continue.  Any other key to quit: " )
        if len( ans.strip() )!= 0:
            break

if __name__=="__main__":
    main()


Cats


# cats1.py
# D. Thiebaut
# program developed in class on 4/1/15
#
class Cat:
    """Cat class.  contains information about a cat: name,
    whether vaccinated, breed, and age"""
    def __init__( self, na, vacc, bree, ag ):
        self.name       = na
        self.vaccinated = vacc
        self.breed      = bree
        self.age        = ag

    def __str__( self ):
        """default string representation for a cat.  Will be use by print() if
        we ask it to print a cat object."""
        if self.vaccinated:
            vac = "vaccinated"
        else:
            vac = "not vaccinated"
        # create the string representation of the object
        s = "{0:10} ==> ({1:1}), {2:1}, {3:1}".format(
            self.name, self.breed, self.age, vac )

        # return the string representation
        return s
    
    def getName( self ):
        """returns the name of the cat"""
        return self.name

    def isVaccinated( self ):
        """returns True if the cat is vaccinated, False otherwise."""
        #if self.vaccinated:
        #    return True
        #else:
        #    return False
        return self.vaccinated

# -------------------------------------------------------------
#                          MAIN
# -------------------------------------------------------------

def main():
    # create an empty list of cats
    catList = []

    # Create 3 cat objects and add them to the list
    # Minou, 3, vaccinated, stray
    #catList.append( Cat( "Minou", True, "stray", 3 ) )
    #catList.append( Cat( "Ralph", False, "Burmese", 1 ) )
    #catList.append( Cat( "Garfield", True, "Orange Tabby", 10 ) )

    # open csv file containing cats.  Example of line in file shown below.
    # Winston, 1, not vaccinated,  stray
    file = open( "cats.csv", "r" )
    lines = file.readlines()
    file.close()

    # the contents of the file is now in a list of strings.  The list is called lines.

    # for each line in the list of lines...
    for line in lines:
        #print( line )

        # split the line into 4 fields
        fields = line.split( ',' )

        # if the line doesn't contain 4 fields, it must be invalid.  Skip it!
        if len( fields ) != 4:
            continue

        # assign each one of the 4 items in the list fields to 4 different variables
        name, age, vacc, breed = fields

        # transform vacc from "vaccinated" or "not vaccinated" to True or False
        if vacc.lower().strip() == "vaccinated":
            vacc = True
        else:
            vacc = False

        # add a new cat with this information to the list of cats
        cat = Cat( name.strip(), vacc, breed.strip(), int(age.strip()) ) 
        catList.append( cat )   
        
    # list all the cats in the list
    for cat in catList:
        print( cat )


    
main()