Programming Languages Code

Chapter 1+2

class Player:

    def __init__(self, name):
        self.name = name
        self.inventory = self.Inventory(name)

    
    class Inventory:
        def __init__(self, name):
            self.name = name
            self.invLi = []

        def addItem(self, c):
            self.invLi.append(c)
            print("%s added to %s's inventory!" % (c, self.name))

        def useItem(self, c):
            self.invLi.remove(c)
            print("%s used %s!" % (self.name, c))

        def listItems(self):
            print("%s's inventory:" % self.name)
            for a in self.invLi:
                print("- %s" % a)


if __name__ == '__main__':
    p1 = Player("Opal")
    p2 = Player("Ffion")
    p3 = Player("Pepper")
    p4 = Player("Miguel")

    p1.inventory.addItem("Bow")
    p1.inventory.addItem("Headband")
    p1.inventory.addItem("Table")
    p2.inventory.addItem("Katana")
    p2.inventory.addItem("Helmet")
    p3.inventory.addItem("Throwing Knives")
    p3.inventory.addItem("Belt")
    p4.inventory.addItem("Sword")
    p4.inventory.addItem("Backpack")
    p4.inventory.addItem("Bandage")

    print("------")

    p1.inventory.listItems()
    p2.inventory.listItems()
    p3.inventory.listItems()
    p4.inventory.listItems()

    print("------")

    p4.inventory.useItem("Bandage")
    p1.inventory.useItem("Table")
    p3.inventory.useItem("Throwing Knives")

    print("------")

    p1.inventory.listItems()
    p2.inventory.listItems()
    p3.inventory.listItems()
    p4.inventory.listItems()

Chapter 3+4

def add(a,b):
    add.count += 1
    c = a+b
    return c

def sub(a,b):
    sub.count += 1
    c = a-b
    return c

def mult(a,b):
    mult.count += 1
    c = a*b
    return c

def div(a,b):
    div.count += 1
    c = a/b
    return c

def printOpts(tot):
    print("------")
    print("Running Total: %s" % str(tot))
    print("------")
    print("[A] Add")
    print("[S] Subtract")
    print("[M] Multiply")
    print("[D] Divide")
    print("[L] List Totals")
    print("[Q] Quit")
    print("------")


if __name__ == '__main__':
    add.count = 0
    sub.count = 0
    mult.count = 0
    div.count = 0
    r = 0

    while True:
        printOpts(r)
        x = input("> ")
        if x in "ASMDLQasmdlq":
            if x.lower() == "a":
                while True:
                    y = input("Type a number to add > ")
                    if y.isdigit():
                        newTot = add(r,int(y))
                        print("Total: %s" % str(newTot))
                        r = newTot
                        break
                    else:
                        print("Error! Invalid input")

            elif x.lower() == "s":
                while True:
                    y = input("Type a number to subtract > ")
                    if y.isdigit():
                        newTot = sub(r,int(y))
                        print("Total: %s" % str(newTot))
                        r = newTot
                        break
                    else:
                        print("Error! Invalid input")

            elif x.lower() == "m":
                while True:
                    y = input("Type a number to multiply > ")
                    if y.isdigit():
                        newTot = mult(r,int(y))
                        print("Total: %s" % str(newTot))
                        r = newTot
                        break
                    else:
                        print("Error! Invalid input")

            elif x.lower() == "d":
                while True:
                    y = input("Type a number to divide > ")
                    if y.isdigit():
                        newTot = div(r,int(y))
                        print("Total: %s" % str(newTot))
                        r = newTot
                        break
                    else:
                        print("Error! Invalid input")


            elif x.lower() == "q":
                break

            elif x.lower() == "l":
                print("Total adds - %s" % str(add.count))
                print("Total subtracts - %s" % str(sub.count))
                print("Total multiplies - %s" % str(mult.count))
                print("Total divides - %s" % str(div.count))


        else:
            print("Invalid input")

        

Chapter 5+6

import time

def add(*a):
    start = time.perf_counter()
    elapsed = start - add.lastTime
    print(f"Time since last use: {elapsed:.4f} seconds")
    add.lastTime = start

    res = 0
    for d in a:
        res += d
    print("Sum: %s" % str(res))
    print("--------")
    return res




if __name__ == '__main__':
    add.lastTime = time.perf_counter()

    print("Type numbers out and type [=] to sum all previous numbers typed. Type [Q] to exit")

    sumLi = ()
    while True:
        x = input("> ")

        if x.isdigit():
            sumLi = sumLi + (int(x),)
        
        elif x.lower() == "q":
            break

        elif x == "=":
            add(*sumLi)
            sumLi = ()

        else:
            print("Error! Invalid Input")


Chapter 7


class Test:

    def __init__(self, ex1):
        self.ex1 = ex1

    def methodTest(self):
        print("Standard test: %s" % self.ex1)

class Mod(Test):

    def __init__(self, ex1):
        self.ex1 = ex1




def newTest(self):
    print("Mod test: %s" % self.ex1)





if __name__ == '__main__':
    class1 = Test("12345")
    Mod.methodTest = newTest
    class2 = Mod('678910')
    

    class1.methodTest()
    class2.methodTest()

    
    

Chapter 8

class ComputerBot:
    def __new__(cls, lang, name):
        if lang == "en":
            return English(name)
        elif lang == "et":
            return Estonian(name)
        elif lang == "it":
            return Italian(name)
        elif lang == "ja":
            return Japanese(name)
        else:
            return super().__new__(cls)
        

class English:
    def __init__(self, name):
        self.name = name
    
    def introduce(self):
        print("Hello! My name is ComputerBot.")

    def greet(self):
        print("Hello %s! Nice to meet you." % self.name)

class Estonian:
    def __init__(self, name):
        self.name = name
    
    def introduce(self):
        print("Tere! Minu nimi on ComputerBot.")

    def greet(self):
        print("Tere %s! Meeldiv tutvuda." % self.name)

class Italian:
    def __init__(self, name):
        self.name = name
    
    def introduce(self):
        print("Ciao! Mi chiamo ComputerBot.")

    def greet(self):
        print("Ciao %s! Piacere di conoscerti." % self.name)

class Japanese:
    def __init__(self, name):
        self.name = name
    
    def introduce(self):
        print("こんにちは!私の名前はComputerBotです。")

    def greet(self):
        print("こんにちは、%sさん!はじめまして。" % self.name)


        




if __name__ == '__main__':
    enBot = ComputerBot("en", "Kaleb")
    etBot =  ComputerBot("et", "Kaisa")
    itBot = ComputerBot("it", "Gio")
    jaBot = ComputerBot("ja", "Yuna")

    enBot.introduce()
    enBot.greet()
    print("----------")
    etBot.introduce()
    etBot.greet()
    print("----------")
    itBot.introduce()
    itBot.greet()
    print("----------")
    jaBot.introduce()
    jaBot.greet()

Chapter 9

def mathMachine(name):
    
    def add(self):
        print("%s + %s = %s" % (str(self.a), str(self.b), str(self.a+self.b)))
    
    def subtract(self):
        print("%s - %s = %s" % (str(self.a), str(self.b), str(self.a-self.b)))

    def constructor(self, a, b):
        self.a = a
        self.b = b

    methods = {
        "__init__": constructor,
        "add": add,
        "subtract": subtract
    }

    return type(name, (object,), methods)



AS_Math = mathMachine("AS_Math")
a1 = AS_Math(4,5)
a1.add()
a1.subtract()

print("------")

a2 = AS_Math(21,4)
a2.add()
a2.subtract()

print("------")


def multiply(self):
    print("%s * %s = %s" % (str(self.a), str(self.b), str(self.a*self.b)))



ASM_Math = mathMachine("ASM_Math")
ASM_Math.multiply = multiply

a3 = ASM_Math(10,3)
a3.add()
a3.subtract()
a3.multiply()

Chapter 10

class Person:

    status = "Player"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def printData(self):
        print("%s - %s" % (self.name, self.status))
        print("Age: %s" % str(self.age))
        print("------")



p0 = Person("Kaleb", 21)
p1 = Person("Reggie", 34)
p2 = Person("Sierra", 23)
p3 = Person("Shafira", 28)

p0.printData()
p1.printData()
p2.printData()
p3.printData()

p0.status = "Host"

p4 = Person("Fletcher", 20)
p0.printData()
p1.printData()
p2.printData()
p3.printData()
p4.printData()

Chapter 11




class Descriptor:

    def __init__(self, name):
        self.name = name

    def __get__(self, instance, owner):
        if instance is None:
            return self
        grade = instance.__dict__.get(self.name)
        print("=========================")
        print("Internal:")
        print("%s's %s: %s" % (instance.name, self.name, grade))
        print("=========================")
        print("Output:")
        return instance.__dict__.get(self.name)
    
    def __set__(self, instance, value):
        grade = instance.__dict__.get(self.name)
        print("=========================")
        print("Internal:")
        print("%s's %s: %s -> %s" % (instance.name, self.name, grade, value))
        print("=========================")
        instance.__dict__[self.name] = value


    
class Student:

    mathGrade = Descriptor("mathGrade")
    scienceGrade = Descriptor("scienceGrade")
    historyGrade = Descriptor("historyGrade")
    englishGrade = Descriptor("englishGrade")

    def __init__(self, name, mathGrade=None, scienceGrade=None, historyGrade=None, englishGrade=None):
        self.name = name
        self.mathGrade = mathGrade
        self.scienceGrade = scienceGrade
        self.historyGrade = historyGrade
        self.englishGrade = englishGrade

        


    
    



if __name__ == '__main__':
    s1 = Student("Eve", 97, 92, 94, 82)
    print(s1.mathGrade)
    print(s1.scienceGrade)
    print(s1.historyGrade)
    s1.englishGrade = 87
    print(s1.englishGrade)

    s2 = Student("Camryn")
    print(s2.scienceGrade)

    s2.englishGrade = 88
    s2.mathGrade = 53
    s2.historyGrade = 76
    s2.scienceGrade = 71

    print(s2.mathGrade)
    print(s2.scienceGrade)
    print(s2.historyGrade)
    print(s2.englishGrade)

Chapter 12

class Messager:

    def __init__(self, username):
        self.username = username

    def log(self, message):
        print("%s: %s" % (self.username, message))

class ChatLog(Messager):

    def __init__(self, username):
        self.username = username
        self.newLine = True

    def log(self, message, timestamp, cont=False):
        if self.newLine:
            print("== %s ==" % timestamp)
        super().log(message)
        if cont == False:
            print("")
            self.newLine = True
        else:
            self.newLine = False


if __name__ == '__main__':

    p1 = ChatLog("Cherry")
    p2 = ChatLog("Tony")
    p3 = ChatLog("Colin")
    p4 = ChatLog("Sherlyn")

    p3.log("Ok what's the plan", "8:32 PM", True)
    p3.log("Do we...", "8:32 PM")
    p1.log("We're going Ballroom", "8:32 PM")
    p2.log("Bruh", "8:33 PM")
    p1.log("Tell them Tony and I are going Vault though", "8:33 PM", True)
    p1.log("Understood?", "8:33 PM", True)
    p1.log("I don't want any leaks...", "8:33 PM", True)
    p1.log("You know what will happen.", "8:33 PM")
    p3.log("Alright", "8:33 PM")
    p4.log("I was drnkning what di di miss", "10:44 PM")