Lab 2

Part 2 Programming Exercise
  1. lab2q1.py
    
    import tkinter as tk
    import random
    
    from shape.taichi import Taichi
    
    def main():
     
        root = tk.Tk()  
        canvas = tk.Canvas(root,height=500,width=500)
        
        for i in range(4):  
            for j in range(4):
                t=Taichi(100+i*100,100+j*100,45,
                         "#%02x%02x%02x"%
                         (int(random.random()*256),
                          int(random.random()*256),
                          int(random.random()*256)),
                         "#%02x%02x%02x"%
                         (int(random.random()*256),
                          int(random.random()*256),
                          int(random.random()*256)),canvas)
                t.draw()    
        
        root.mainloop()  
    
    if __name__ == '__main__':
        main()  
    
  2. lab2q2.py
    
    def main():
            loanAmount = float(input("The loan amount is : "))
            annualInterestRate = float(input("The annual interest rate is: "))
            monthlyPayment = float(input("The monthly payment is: "))
    
            month = 1
            startingBalance = loanAmount
            payment = monthlyPayment
            middleBalance = loanAmount - payment
            interest = middleBalance * annualInterestRate/12/100
            endingBalance = middleBalance + interest
            
            print("\n")
            print("%25s%30s%30s"%
                  ("Starting","Middle","Ending"))
            print("%10s%15s%15s%15s%15s%15s"%
                  ("Month","Balance","Payment","Balance","Interest","Balance"))
            print("-"*85)
                  
            while startingBalance > 0:
                print("%10d%15.2f%15.2f%15.2f%15.2f%15.2f"%
                  (month,startingBalance,payment,middleBalance,interest,endingBalance))
                
                month+=1
                startingBalance = endingBalance
                
                if endingBalance > monthlyPayment:
                    payment = monthlyPayment
                else: payment = endingBalance
                
                middleBalance =  startingBalance - payment
                interest = middleBalance * annualInterestRate/12/100
                endingBalance = middleBalance + interest
                
    if __name__ == "__main__":
        main()
    
  3. lab2q3.py
    
    fileIn = open('datafile1.dat', 'r')
    
    clientDT=['Name','Address','Balance']
    clientDL=[]
    line = fileIn.readline()
    
    while line != '':
        clientRec=line.split('_')
        if len(clientDL) == 0:
            if clientRec[2] == 'D':
                clientDL.append(dict(zip(clientDT,
                                         [clientRec[0],clientRec[1],float(clientRec[3])])))
            else:
                clientDL.append(dict(zip(clientDT,
                                         [clientRec[0],clientRec[1],-float(clientRec[3])])))            
        else: 
            i = 0
            while i < len(clientDL) and clientDL[i]['Name'] != clientRec[0]:
                i += 1
                
            if i == len(clientDL):
                if clientRec[2] == 'D':   
                    clientDL.append(dict(zip(clientDT,
                                             [clientRec[0],clientRec[1],float(clientRec[3])])))
                else:
                    clientDL.append(dict(zip(clientDT,
                                             [clientRec[0],clientRec[1],-float(clientRec[3])])))                
            else:
                if clientRec[2] == 'D':
                    clientDL[i]['Balance'] += float(clientRec[3])
                else: clientDL[i]['Balance'] -= float(clientRec[3])
                
        line = fileIn.readline()
                
    print('%-20s%-30s%10s'%(clientDT[0],clientDT[1],clientDT[2]))
    print('='*60)    
    for e in sorted(clientDL, key = lambda c: c['Name']):
        if e['Balance'] != 0:
            print('%-20s%-30s%10.2f'%(e['Name'],e['Address'],e['Balance'])) 
              
    fileIn.close()
    
  4. lab2q4.py
    
    #!%python path%/python.exe
    import time
    import cgi
    
    html5top='''
    <!-- {fname} -->
    <!DOCTYPE html>
    <html>
     <head>
      <title>{title}</title>
     </head>
     <body>
      <h1>{header}</h1>
    '''
    html5bottom='''
     </body>
    </html>
    '''
    
    print (html5top.format(fname='cgilogon.py', title='CGI',header='Logon'))
    
    form = cgi.FieldStorage()
    
    if 'name' in form:
        if form['password'].value == 'abc':
            print ("<h1>Welcome, %s!</h1>" % form[ 'name' ].value)
            print ("My PDP")
        else: print ("<h1>password incorrect %s!</h1>" % form[ 'password' ].value)
    
    print (time.ctime( time.time() ))
    print (html5bottom)
     
    
  5. lab2q5.py
    
    #!%python path%/python.exe
    import time
    import urllib.request
    
    fileIn=urllib.request.urlopen('http://personal.cityu.edu.hk/~dcywchan/2004dco10803/datafile1.txt')
    byteStr = fileIn.read()
    lines=byteStr.decode('utf-8')
    lineSep=lines.split('\r\n')
    
    clientDT=['Name','Address','Balance']
    clientDL=[]
            
    for e in lineSep:
        if e != '':
            clientRec=e.split('_')
            if len(clientDL) == 0:
                if clientRec[2] == 'D':
                    clientDL.append(dict(zip(clientDT,
                                         [clientRec[0],clientRec[1],float(clientRec[3])])))
                else:
                    clientDL.append(dict(zip(clientDT,
                                         [clientRec[0],clientRec[1],-float(clientRec[3])])))            
            else: 
                i = 0
                while i < len(clientDL) and clientDL[i]['Name'] != clientRec[0]:
                    i += 1
                
                if i == len(clientDL):
                    if clientRec[2] == 'D':   
                        clientDL.append(dict(zip(clientDT,
                                             [clientRec[0],clientRec[1],float(clientRec[3])])))
                    else:
                        clientDL.append(dict(zip(clientDT,
                                             [clientRec[0],clientRec[1],-float(clientRec[3])])))
                else:
                    if clientRec[2] == 'D':
                        clientDL[i]['Balance'] += float(clientRec[3])
                    else: clientDL[i]['Balance'] -= float(clientRec[3])
    
    html5top='''
    <!-- {fname} -->
    <!DOCTYPE html>
    <html>
     <head>
      <title>{title}</title>
     </head>
     <body>
      <h1>{header}</h1>
    '''
    html5bottom='''
     </body>
    </html>
    '''
    tableHeader='''
    <table border=1>
    <tr><th>Name</th><th>Address</th><th>Balance</th></tr>
    '''
    print (html5top.format(fname='lab2q5.py',title='Simple Billing Web Page',header='Customer Table'))
    
    print(tableHeader)
    
    for e in sorted(clientDL, key = lambda c: c['Name']):
        if e['Balance'] != 0:
            print ('<tr><td>'+e['Name']+'</td>'+
                   '<td>'+e['Address']+'</td>'+
                   '<td>'+str(e['Balance'])+'</td></tr>')
    
    print('</table>')
    print('<p />')
    
    print (time.ctime( time.time() ))
    print (html5bottom)
    
    fileIn.close()