Showing posts with label ITC110. Show all posts
Showing posts with label ITC110. Show all posts

Saturday, November 16, 2019

Code for Assignment 8 Video

Customer Class

'''
Class called Customer
Every customer has a name,
number, email, phone and they
can collect rewards points
An object is collection of related
functions. They all relate
to one topic like customer.
The idea is to make it easier
to manage complex code
by breaking it into the kinds
of objects that actually make up
the contents of the program
abstraction
encapsulation
inheritance
polymorphism
'''
class Customer():
    def __init__(self, number, name, phone, email, rewards):
        self.number=number
        self.name=name
        self.phone=phone
        self.email=email
        self.rewards=rewards

    def setPhone(self, phone):
        self.phone=phone

    def getPhone(self):
        return self.phone

    def getName(self):
        return self.name

    def getEmail(self):
        return self.email

    def getRewards(self):
        return self.rewards

    def addRewards(self, points):
        self.rewards += points

    def useRewards(self, points):
        self.rewards = self.rewards-points

    def __str__(self):
        return str(self.number) + ", " + self.name
    

Item Class

'''
class item
It will represent an item to purchase
It will have a number, a name and a price
'''
class Item():
    def __init__(self, number, name, price):
        self.number=number
        self.name=name
        self.price=price

    def getNumber(self):
        return self.number

    def getName(self):
        return self.name

    def getPrice(self):
        return self.price
    

Purchase Class

'''
Purchase class
to show purchase of an item
it will have a list of items
and methods for
Totaling the purchase
and totaling the points
str method that outputs
basically a receipt
'''
class Purchase():
    def __init__(self):
        self.items=[]

    def addItem(self, item):
        self.items.append(item)

    def totalItems(self):
        total=0
        for item in self.items:
            total += item.price
        return total

    def totalPoints(self):
        total=self.totalItems()
        points=int(total)
        return points

    def __str__(self):
        receipt=""
        for item in self.items:
            receipt =receipt + item.name +"\t\t" + str(item.price) + "\n"
        total = self.totalItems()
        receipt=receipt + "\t\t" + str(total)
        return receipt
    
    

Main

from customer import Customer
from item import Item
from purchase import Purchase

def main():
    cust=Customer(123, 'Steve', 'steve@spconger.com', '2065551234', 0)
    purch = Purchase()
    cont='y'
    while cont=='y':
        itemNumber=int(input('Enter item Number. '))
        itemName=input("Enter item name ")
        itemPrice=float(input("Enter item price "))
        item=Item(itemNumber, itemName, itemPrice)
        purch.addItem(item)
        cont=input("Add another item? y to continue. " )
        cont=cont.lower()
    print(purch)
    cust.addRewards(purch.totalPoints())
    print ("your total rewards are", cust.getRewards())

main()
                             

Sunday, November 10, 2019

Customer and customer test code from peer 8 video

'''
Class called Customer
Every customer has a name,
number, email, phone and they
can collect rewards points
An object is collection of related
functions. They all relate
to one topic like customer.
The idea is to make it easier
to manage complex code
by breaking it into the kinds
of objects that actually make up
the contents of the program
abstraction
encapsulation
inheritance
polymorphism
'''
class Customer():
    def __init__(self, number, name, phone, email, rewards):
        self.number=number
        self.name=name
        self.phone=phone
        self.email=email
        self.rewards=rewards

    def setPhone(self, phone):
        self.phone=phone

    def getPhone(self):
        return self.phone

    def getName(self):
        return self.name

    def getEmail(self):
        return self.email

    def getRewards(self):
        return self.rewards

    def addRewards(self, points):
        self.rewards += points

    def useRewards(self, points):
        self.rewards = self.rewards-points

    def __str__(self):
        return str(self.number) + ", " + self.name
    

Customer test

from customer import Customer

def main():
    c1 = Customer(123, 'Joe Smith', '2065551234', 'js@gmail.com', 10)
    print(c1)
    c1.addRewards(20)
    print(c1.getRewards())
    c1.useRewards(13)
    print(c1.getRewards())
    print(c1.getEmail())
    c2=Customer(234, 'Lynn Jones', '2065553456', 'Lynn@gamail.com',100)
    print("******************")
    print(c1)
    print()
    print(c2)

main()

Monday, October 28, 2019

if and while blocks

'''
a=5
b=10
if a < b:
    print(a, "is smaller thant", b)
elif a > b:
    print (a, " is bigger than ", b)
else:
    print (a, "is equal to ",b)
'''

def getGrade():
    grade=-1
    while grade < 0 or grade > 100:
        grade=int(input("Enter a grade between 0 and 100 "))
    #if grade < 0 or grade > 100:
        #grade=-1       
    return grade
                    
def evaluateGrade():
    g = getGrade()
    #if g == -1:
        #print ("Invalid Grade")
        #return
       
    if g > 90:
        print("you did great")
    elif g > 80:
        print(" you did good")
    elif g > 70:
        print("you passed")
    else:
        print("Sorry, you failed.")

def main():
    choice='y'
    while choice == 'y':
        evaluateGrade()
        choice=input("y to continue")
        choice.lower()

main()

Tuesday, October 8, 2019

Code from chapter 6 video

'''
Functions divide code into blocks.
Each function should do one thing.
Functions make it easier to debug and manage
program flow.
A function can just execute its code and be done.
A function can take in parameters to work with.
A function can return a value.
We are going to do a very simple program to calculate area
this requires the following steps
1. print out of what the program does
2. get the length and width of the area in feet
3. calculate the area
4. Output the results
Each step will be a separate function.
'''
def intro():
    print("This program calculates area")

def getLength():
    length=eval(input("enter the length: "))
    return length

def getWidth():
    width=eval(input("Enter the width: "))
    return width

def calculateArea():
    l=getLength()
    w=getWidth()
    a=l * w
    outputArea(a)

def outputArea(area):
    print("the area is", area)

def main():
    intro()
    calculateArea()

main()


    

Code from chapter 5 Video

Here is the console interactive session

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> #Chapter 5 take IV
>>> #strings
>>> #lists of characters
>>> greeting="Hello"
>>> type(greeting)
<class 'str'>
>>> number='17'
>>> type(number)
<class 'str'>
>>> print[greeting[0])
SyntaxError: invalid syntax
>>> print(greeting[0])
H
>>> print(greeting[4])
o
>>> print(greeting[2:3])
l
>>> print(greeting[2:4})
SyntaxError: invalid syntax
>>> print(greeting[2:4])
ll
>>> print(greeting[:4])
Hell
>>> len(greeting)
5
>>> for ch in greeting:
 print(ch)

H
e
l
l
o
>>> 
====== RESTART: C:/Users/SteveConger/Documents/PythonFiles/username.py ======
This program generates user names
enter your first name: Steve
enter your last name: Conger
Your user name is SConger
>>> 
====== RESTART: C:/Users/SteveConger/Documents/PythonFiles/username.py ======
This program generates user names
enter your first name: Steve
enter your last name: Robertson
Your user name is sroberts
>>> #page 148 string functons
>>> ord(a)
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    ord(a)
NameError: name 'a' is not defined
>>> ord("a")
97
>>> ord("A")
65
>>> chr(97)
'a'
>>> weekdays=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
>>> print(weekdays[3])
Thu
>>> print(weekends[3-1])
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    print(weekends[3-1])
NameError: name 'weekends' is not defined
>>> print (weekdays[3-1])
Wed
>>> num=1234.33939020229202
>>> print("the formatted value = {0000.2f}".format(num))
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    print("the formatted value = {0000.2f}".format(num))
AttributeError: 'float' object has no attribute '2f'
>>> print("the formatted value={0:0.2f}".format(num))
the formatted value=1234.34
>>> print("The formatted value=${0.0.2f}".format(num))
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    print("The formatted value=${0.0.2f}".format(num))
AttributeError: 'float' object has no attribute '0'
>>> print("the formatted value=${0:0.2f}",format(num))
the formatted value=${0:0.2f} 1234.339390202292
>>> print("the formatted value=${0:0.2f}".format(num))
the formatted value=$1234.34
>>> 
====== RESTART: C:/Users/SteveConger/Documents/PythonFiles/userfile.py ======
this program creates a file of usernames in batch mode
from a file of names
Enter the file name with the names: name.txt
Enter the name of the output file: unames.txt
Traceback (most recent call last):
  File "C:/Users/SteveConger/Documents/PythonFiles/userfile.py", line 26, in <module>
    main()
  File "C:/Users/SteveConger/Documents/PythonFiles/userfile.py", line 12, in main
    infile=open(infileName, "r")
FileNotFoundError: [Errno 2] No such file or directory: 'name.txt'
>>> 
====== RESTART: C:/Users/SteveConger/Documents/PythonFiles/userfile.py ======
this program creates a file of usernames in batch mode
from a file of names
Enter the file name with the names: names.txt
Enter the name of the output file: unames.txt
Traceback (most recent call last):
  File "C:/Users/SteveConger/Documents/PythonFiles/userfile.py", line 26, in <module>
    main()
  File "C:/Users/SteveConger/Documents/PythonFiles/userfile.py", line 19, in main
    print(username, file=outfile)
NameError: name 'outfile' is not defined
>>> 
====== RESTART: C:/Users/SteveConger/Documents/PythonFiles/userfile.py ======
this program creates a file of usernames in batch mode
from a file of names
Enter the file name with the names: names.txt
Enter the name of the output file: unames.txt
the user names have been written to unames.txt
>>> 

Here is the first version of the Username program

#username.py
#Steve Conger
#10/8/2019

def main():
    print("This program generates user names")

    #get user first and last names
    first=input("enter your first name: ")
    last=input("enter your last name: ")

    #concatinate user name first letter of first name
    #first 7 letters of the last name
    username=first[0] + last[:7]
    print("Your user name is",username.lower())

main()

Here is the file version

#create a file of usernames
#read the file

def main():
    print("this program creates a file of usernames in batch mode")
    print("from a file of names")

    # get file names
    infileName=input("Enter the file name with the names: ")
    outfileName=input("Enter the name of the output file: ")

    infile=open(infileName, "r")
    outfile=open(outfileName, "w")

    # loop through the file, process and write
    for line in infile:
        first, last = line.split()
        username=(first[0] + last[:7]).lower()
        print(username, file=outfile)

    infile.close()
    outfile.close()

    print ("the user names have been written to", outfileName)

main()

        

Thursday, September 26, 2019

Python from First Class

First Program

'''
This is a python program
showing some basic elements
Steve 9-26-2019
'''

def main():
    #variables and assignments
    number1 = 7
    number2 = 12

    #print results
    print(number1+number2)

main()
    

Math Operators

'''
This program will ouput some
math based on user inputs
Steve Conger 9-26-2019
'''
def mathOperators():
    #getting input
    nameOfUser=input('Enter your name: ')
    number1, number2 = eval(input("Please enter two numbers divided with a comma: "))
    
    addition =number1 + number2
    subtraction=number1 - number2
    mult = number1 * number2
    division = number1 / number2
    intdivision = number1 // number2
    remainder = number1 % number2 #modulus

    print ("sum",addition)
    print ("difference",subtraction)
    print ("product", mult)
    print("Quotient", division)
    print("integer",intdivision)
    print("remainder", remainder)
    print(nameOfUser)


mathOperators()

Loop

def main():
    word = input("Enter a word")
    for i in range(10):
        print(i, word)

main()

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()
    

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()

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')

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()