Tuesday, December 4, 2018

Assignment 8. Grades

grade.py

class Grade():
    def __init__(self, course, credits, score):
        self.course=course
        self.credits=credits
        self.score=score
    
    def getCourse(self):
        return self.course
    
    def getCredits(self):
        return self.credits
    
    def getScore(self):
        return self.score

Student.py

from grade import Grade

class Student():
    def __init__(self, SID, name, email):
        self.SID =SID
        self.name=name
        self.email=email
        self.grades=[]

    def getSID(self):
        return self.SID
    
    def getName(self):
        return self.name
    
    def getEmail(self):
        return self.email
    
    def addGrade(self,grade):
        self.grades.append(grade)
    
    def getGrades(self):
        return self.grades
    
    def calculateGPA(self):
        totalCredits=0.0
        totalWeight=0.0
        gpa=0.0
        if len(self.grades) != 0:
            for i in range(len(self.grades)):
                totalCredits += self.grades[i].credits
                totalWeight += self.grades[i].credits * self.grades[i].score
            gpa = totalWeight / totalCredits
        return gpa

    def __str__(self):
        return self.SID + " " + self.name + " " + self.email

StudentDisplay.py

from grade import Grade
from student import Student

class Display():
    def __init__(self):
        self.makeStudent()
        self.enterGrades()
        self.outputStuff()

    def makeStudent(self):
        sid = input("Enter the student SID ")
        name= input(" Enter the student name ")
        email=input("Enter the student emai ")
        self.student = Student(sid,name,email)
    
    def enterGrades(self):
        done='n'
        while done == 'n':
            course=input("Enter the course name ")
            credits=float(input("Enter the number of credits "))
            finalGrade=float(input("Enter the final grade "))
            self.grade =Grade(course, credits, finalGrade)
            self.student.addGrade(self.grade)
            done = input("Done n. y to quit ")
            done=done.lower()
    
    def outputStuff(self):
        print(self.student)
        gradeList=self.student.getGrades()
        for i in range(len(gradeList)):
            print(gradeList[i].course, gradeList[i].credits, gradeList[i].score)
        gpa = self.student.calculateGPA()
        print ("The GPA is ", gpa)

def main():
    display=Display()

main()
    

Wednesday, November 28, 2018

Show Tracker JSON Afternoon

{
  name :'Triple Door',
  address : '216 Union street, Seattle ',
  restrictions : 'sometimes',
  parking : 'bus recommended',
  url : 'http://www.triple.net',
  email : 'tripledoor@gmail.com ',
  phone : '2065551234',
  description : 'restaurant and music lounge'
}

{
   name : 'An intimate evening',
   venue : {name:'Triple Door ',  url : 'http://www.triple.net'},
   artists : [{name: 'The Paper Boys', genre: 'Jazz'}, 
             {name : 'Mitzki', genre: ['alt rock', 'folk']}],
   datetime : ISODate('2018-12-07T20:00:00'),
   price : [{type: 'general', cost : 80.00}, 
            {type : 'VIP', cost : 120.00} ],
}

[{
   fanname : 'showgoer ',
   email : 'showgoer@gmail.com ',
   artists: ['Death Cab For Cutie','Imagine Dragons' ],
   genres : ['alt rock', 'pop' ]

},
{
   fanname : 'neversaydie ',
   email : 'nsd@msn.com',
   artists: ['Mitzki','Bob Dylan'],
   genres : ['alt rock', 'folk' ]

}]

show tracker JSON

{
  name: 'Deck The Hall Ball',
  date : ISODate('2018-12-11T17:00:00'),
  artist : [{name: 'Death Cab for Cutie', genre : 'alt rock'},
            {name: 'Billie Eilish', genre : 'alt rock'},
            {name: 'Young the Giant', genre : 'alt rock'}],
  price : [{type: 'general', amount : 60.00},
           {type: 'reserved', amount : 80.00}],
  venue : {name : 'WaMu Theater', 
           address : '800 Occidental Ave,South',
           URL : 'http://centrylink.com'},
   restrictions : 'no food, no drinks',
   parking : 'On site parking. Next to light rail'
}

[{
  username : 'showgoer',
  email : 'showgoer@gmail.com',
  artists : ['Death cab for Cutie', 'Neil Young', 'Lorde'],
  genres : ['alt rock', 'rock', 'folk']
},
{
  username : 'readytorock',
  email : 'rtor@msn.com',
  artists : ['Metalica', 'Iron Maiden', 'Black Sabbath']
}]

Two more shows

[{
   name : 'Deck the Hall Ball',
   venue : {name:'WaMu Theater',  url : 'http://www.WaMu.com'},
   artists : [{name: 'Death Cab for Cutie', genre: ['alt','pop']}, 
             {name : 'Billie Eilish', genre: ['alt rock', 'pop']}],
   datetime : ISODate('2018-12-11T20:00:00'),
   price : [{type: 'general', cost : 80.00}, 
            {type : 'VIP', cost : 120.00} ],
},
{
   name : 'Bob Dylan',
   venue : {name:'Paramount',  url : 'http://www.Paramount.com'},
   artists : {name: 'Bob Dylan', genre: ['rock', 'folk']},           
   datetime : ISODate('2019-02-07T20:00:00'),
   price : [{type: 'general', cost : 80.00}, 
            {type : 'VIP', cost : 120.00} ],
}]

Two more fans

[{
   fanname : 'superfan',
   email : 'superfan@gmail.com ',
   artists: ['Death Cab For Cutie','Billie Eilsih' ],
   genres : ['alt rock', 'pop' ]

},
{
   fanname : 'concertgoer ',
   email : 'concertgoer@msn.com',
   artists: ['Mitzki','Bob Dylan', 'Neil Young'],
   genres : ['alt rock', 'folk' ]

}]

Tuesday, November 27, 2018

Mileage class and Card Class

Mileage.py

class Mileage:
    def __init__(self, miles, gallons):
        self.miles=miles
        self.gallons=gallons
        self.pricePerGallon = 0.0
    
    def getMiles(self):
        return self.miles

    def getGallons(self):
        return self.gallons
    
    def setPricePerGallon(self,price):
        self.pricePerGallon=price
    
    def getPricePerGallon(self):
        return self.pricePerGallon
    
    def calculateMPG(self):
        return self.miles/self.gallons
    
    def calculatePricePerMile(self):
        result=0.0
        if self.pricePerGallon != 0:
            cost=self.pricePerGallon * self.gallons
            result=cost/self.miles
        return result

    def __str__(self):
        return str(self.miles) + ' miles ' + str(self.gallons) + ' gallons'

Display.py

from mileage import Mileage

class Display:
    def __init__(self):
        self.miles=self.getMiles()
        self.gallons=self.getGallons()
        self.mileage=Mileage(self.miles, self.gallons)

    def getMiles(self):
        self.miles = float(input("Enter the total miles: "))
        return self.miles

    def getGallons(self):
        self.gallons=float(input("Enter the total gallons "))
        return self.gallons
    
    def getMPG(self):
        #self.miles=self.getMiles()
        #self.gallons=self.getGallons()
        #self.mileage = Mileage(self.miles, self.gallons)
        self.mpg=self.mileage.calculateMPG()
    
    def getPricePerMile(self):
        price=eval(input("enter the price per gallon "))
        self.mileage.setPricePerGallon(price)
        self.ppm=self.mileage.calculatePricePerMile()
    
    def displayanswers(self):
        self.getPricePerMile()
        self.getMPG()
        print(" the mileage is ", self.mpg)
        print(" The price per miles is", self.ppm)


def main():
    display = Display()
    display.displayanswers()
        
main()

Card.py

#Card
class Card:
    def __init__(self, rank, suit):
        self.rank=rank
        self.suit=suit
        self.value=0
       
        
    def getRank(self):
        return self.rank

    def getSuit(self):
        return self.suit

    def getValue(self):
        if self.rank > 10:
            self.value=10
        else:
            self.value=self.rank
        return self.value

    def setSuit(self):
        self.su=""
        if self.suit =="d":
            self.su="diamonds"
        elif self.suit=="h":
            self.su="hearts"
        elif self.suit=="s":
            self.su="spades"
        else:
            self.su ="clubs"
        return self.su

    
    
    def __str__(self):
        
        if self.rank >1 and self.rank< 11:
            self.name=str(self.rank) + " of " + self.setSuit()
        if self.rank==1:
            self.name="the ace of " + self.setSuit()
        if self.rank==11:
            self.name="the jack of " + self.setSuit()
        if self.rank==12:
             self.name="the queen of " + self.setSuit()
        if self.rank==13:
             self.name="the king of " + self.setSuit()
        return self.name

def main():
    card=Card(9,"s")
    print(card)

main()

Monday, November 26, 2018

JSON Afternoon

productReviews

rating

db.products.insert(
{
  '_id' : 1,
  'productname' : 'Ipad Pro',
  'price' : [799.99, 1000.00, 2300.00],
  'company' : 'Apple',
  'producttype' : 'tablet'
}
)


reviewers
{
   'reviewername' : 'Shirley Walker',
   'email' : 'sw@gmail.com'
}

reviews
[{
   'title' : 'The Ipad family of tablets',
   'reviewdate' : '11/26/2018',
   'rating' : 4.5,
   'product' : {
                 'productid' : 1,
                 'productname' : 'Ipad Pro',
                 'price' : [799.99, 1000.00, 2300.00],
                 'producttype' : 'Tablet'
               },
  'reviewer' : {
                 'reviewername' : 'Shirley Walker',
                 'email' : 'sw@gmail.com' 
               },
   'reviewtext' : 'Ipads are fun'
},
{
   'title' : 'Microsoft Surface',
   'reviewdate' : '11/26/2018',
   'rating' : 4,
   'product' : {
                 'productid' : 2,
                 'productname' : 'Microsoft Surface',
                 'price' : [799.99, 12000.00],
                 'producttype' : 'Tablet'
               },
  'reviewer' : {
                 'reviewername' : 'Hunter S. Thompson',
                 'email' : 'ht@gmail.com' 
               },
   'reviewtext' : 'expensive, underpowered laptops'
}]

JSON Examples

use ProductReveiws

collections are like tables--collections of JSON objects

collection products

{
   '_id' : 1,
   'productname' : 'Ipad mini',
   'price' : [300.99,600.99,800.99],
   'company' : 'Apple',
   'storage' : '128 gigabytes'
}

collection reviewers
{
    'reviewername' : 'Norman Bates',
    'email' : 'nb@gmail.com'
    
}

collection reviews
[{
   'reviewtitle' : 'Ipad minis, a nice size',
   'reviewdate' : '11/26/2018',
   'rating' : 4,
   'reviewtext' : 'easier to hold than a full sized ipad',
   'product' : {
                 'productid' : 1, 
                 'productname' : 'Ipad mini',
                 'productprice' : 300.99
                },
    'reviewer' : {
                   'reviewername': 'Norman Bates',
                   'email' : 'nb@gmail.com'
                  }

}, 
{
   'reviewtitle' : 'Mac Pro, a nice size',
   'reviewdate' : '11/28/2018',
  
   'reviewtext' : 'easier to hold than a full sized ipad',
   'product' : {
                 'productid' : 2, 
                 'productname' : 'Mac Pro',
                 'productprice' : 1200.99,
   'company' : 'Apple',
                 'soldat' : 'Applestore'
                },
    'reviewer' : {
                   'reviewername': 'John Manning',
                   'email' : 'jm@gmail.com'
                  }

}], 

Tuesday, November 20, 2018

First objects

Door class and tests

class Door:
    def __init__(self, number):
        self.number=number
        self.locked=True
        self.open=False
    
    def unlock(self):
        self.locked=False
    
    def lock(self):
        if self.open==False:
            self.locked=True
    
    def openDoor(self):
        if self.locked==False:
            self.open=True
    
    def closeDoor(self):
        self.open=False
        self.locked=True

    def __str__(self):
        if self.open==True:
            self.status="the door is open and unlocked"
        
        elif self.locked==False and self.open==False:
            self.status= "The door is unlocked and ready to open"
        else:
            self.status="the door is closed and locked"
    
        return self.status
        

def main():
    door=Door(3176)
    print ("lets unlock the door") 
    door.unlock()
    print(door)
    print ("let's open the door")
    door.openDoor()
    print(door) 
    print ("let's shut and lock it")
    door.closeDoor()
    print(door)

main()     

MSDie class

from random import randrange
class MSDie:
    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

TestDie class (You must have an __init__.py file in the directory to be able to import.)

from die import MSDie
def main():
    d1=MSDie(12)
    d2=MSDie(12)
    d1.roll()
    d2.roll()
    print(d1.getValue())
    print(d2.getValue())

main()

Thursday, November 8, 2018

More while loops

Here is a modified version of the grade averaging program

def getGrade():
    grade=float(input("Enter a grade: "))
    return grade

def storeGrades():
    grades=[]
    grade=0
    print ("Enter grades. -1 to exit")
    #this is an example of a sentinal loop
    while grade >= 0:
        grade=getGrade()
        if grade <0:
            break
        grades.append(grade)
        
    print (grades)
    return grades

def getAverage():
    gradeList=storeGrades()
    avg = 0
    total=0
    for g in range(len(gradeList)):
        total += gradeList[g]
    avg=total / len(gradeList)
    return avg

def display():
    avg=getAverage()
    
    print ("the average grade is", avg)

def main():
    display()

main()

Here are the other two while loops, while True and while quit=no

while True:
    print ('Hello')
    exit = input("quit y/n")
    if exit=='y':
        break
print ('loop done')

quit='n'
while quit == 'n':
    print ('Hello')
    quit = input("quit y/n")
    quit=quit.lower()
print ('Loop2 done')

Wednesday, November 7, 2018

SQL in MySQL

Use Pythonclub3;
use Sakila;
Select * from Film;

/*this joins three tables*/
Select first_name, Last_name, title
From Actor
Join film_actor
On actor.actor_id=film_actor.actor_id
join Film
on film.film_id=film_actor.film_id
Where title='Academy Dinosaur';

Insert into Actor (first_name, Last_name)
values('HARRISON','FORD');

Select * from actor;

start transaction; 
Update Actor
Set First_name='ALEC'
Where actor_id=1;
commit;

Select * from Actor;

Start Transaction;
Update Actor
Set last_name='Smith';
rollback;

Tuesday, November 6, 2018

Indefinite Loops

First take

def main():
    #basic for loop (definite loops)
    for i in range(10):
       print("h1, vote")

    #indefinite loop
    total=0
    avg=0
    grade=0
    counter =0
    while grade >=0:
        grade=float(input("Enter grade -1 to exit: "))
        if grade ==-1:
            break
        total += grade
        #total = total + grade
        counter += 1
        print(counter)
    
    avg = total/counter
   
    print ("the average score is", avg)


main()

Menu loop

def menu():
    print ("Type the menu number for your option.")
    choice=0
    while choice !=5:
        print("1: birthday:")
        print("2: christmas: ")
        print("3: new years")
        print('4: thanksgiving')
        print('5: Exit')
        choice=int(input("Enter your choice"))

        if choice != 5:
            managechoices(choice)
        
def managechoices(choice):
    if choice==1:
        birthday()
    elif choice == 2:
        christmas()
    elif choice==3:
        newyears()
    else:
        thanksgiving()

def birthday():
    print("happy birthday")

def christmas():
    print ("merry christmas")

def newyears():
    print ("happy new years")

def thanksgiving():
    print( "I ate way too much")

def main():
    menu()

main()

      

Another example with grades and average using functions

def getGrade():
    grade=float(input("Enter a grade: "))
    return grade

def storeGrades():
    grades=[]
    grade=0
    print ("Enter grades. -1 to exit")
    #this is an example of a sentinal loop
    while grade >= 0:
        grades.append(grade)
        grade=getGrade()
    return grades

def getAverage():
    gradeList=storeGrades()
    avg = 0
    total=0
    for g in range(len(gradeList)):
        total += gradeList[g]
    avg=total / len(gradeList)
    return avg

def display():
    avg=getAverage()
    print ("the average grade is", avg)

def main():
    display()

main()