Friday 3 August 2012

Python - Last Minute Code

Two weeks back I attended a much awaited training to learn python. The syntax was (funny) new and needed attention to (whitespaces) details. After the training was over (phew...) we had to submit a script code!!!
This was the time to put my learning (graspings) to test.
Posting below the code that I wrote (Incomplete though) just to keep an archive of how python works:


class Stock:
def __init__(self, stockTicker, stockName, purSize, purPrice):
self.Ticker=stockTicker
self.Name=stockName
self.PurchaseSize=purSize
self.PurchasePrice=purPrice

def __str__(self):
return '%s,%s,%d,%f' % (self.Ticker,self.Name,self.PurchaseSize,self.PurchasePrice)


def main():
choice='x'
while choice.upper()!='Q':
createMenu();
choice = raw_input('\n\t:\>')


if choice.upper()=='A':
addStocks();
if choice.upper()=='L':
loadFile();
if choice.upper()=='D':
deleteStock();
#--------------- End of Main Method ---------------------#


def addStocks():
tckr = raw_input('Ticker: ')
name = raw_input('Name: ')
size = input('No. of Shares: ')
price = input('Purchase Price: ')
stk = Stock(tckr,name,size,price)
saveStockInFile(stk);
#--------------- End of addStocks Method ---------------------#


def deleteStock():
stkTicker = raw_input('Ticker: ')
filePtr = open('MyPortfolio.txt', 'r');
del LoadedStocks[:]
while True:
try:
LoadedStocks.append(pickle.load(filePtr));
except EOFError:
break;



for stk in LoadedStocks:
if stk.Ticker == stkTicker:
LoadedStocks.remove(stk);
break;

filePtr.close();
filePtr = open('MyPortfolio.txt', 'w');
filePtr.write('');
filePtr.close();


for stk in LoadedStocks:
saveStockInFile(stk)
#--------------- End of deleteStock Method ---------------------#


def loadFile():
filePtr = open('MyPortfolio.txt', 'r');
del LoadedStocks[:]
while True:
try:
LoadedStocks.append(pickle.load(filePtr));
except EOFError:
break;


filePtr.close();


for stk in LoadedStocks:
print str(stk)
#--------------- End of loadFile Method ---------------------#


def createMenu():
print '\n\t\tWelcome to Portfolio Manager (ver 1.0)'
print '\t\t--------------------------------------'
print '\n - What would you like to do Today?'
print '\n\t(A)dd Stocks\n\t(D)elete Stocks\n\t(L)oad File\n\t(U)pdate Prices\n\t(R)eport\n\t(Q)uit:'


def saveStockInFile(stk):
filePtr = open('MyPortfolio.txt', 'a');
#line = 'Ticker=%s\nName=%s\nShares=%d\nPurchase Price=%f'%(stk.Ticker, stk.Name, stk.PurchaseSize, stk.PurchasePrice)
#filePtr.write(line)
pickle.dump(stk, filePtr)
filePtr.flush();
filePtr.close();


import pickle;
LoadedStocks = []
main();

No comments:

Post a Comment