2015-05-13 57 views
0

好,所以我需要創建一個更新(全局變量)銀行賬戶的東西。我的指示如下:python 3.0函數內功能

def setBalance(amt):  # Defines (but doesn't print) the value of the account balance 
def printBalance():  # Displays current balance as a money value with a heading 
def printLedgerLine(date, amount, details): # with items (and the balance) spaced and formatted 
def deposit (date, details, amount): # Alter the balance and print ledger line  
def withdraw(date, details, amount): # Alter the balance and print ledger line 

因此,當我做這樣的事情;

deposit ("23-12-2012", "Income", 225) 
withdraw("24-12-2012", "Presents", 99.02) 
printBalance() 

它會返回;

23-12-2012 Income    $ 225.00  $ 575.01 
24-12-2012 Presents   $ 99.02  $ 475.99 
Current Balance is $ 475.99 

我不知道該怎麼做。目前,我正在定義printLedgerLine來獲取信息並用製表符打印,因此看起來不錯。 然後我在退出或存款中調用它,並試圖在最後打印(新)餘額。

def deposit(date, details, amount): 
    global balance 
    balance = float(balance) + float(amount) 
    printLedgerLine(date,amount,details) 
    print(str(balance) 

這可以工作,但打印它們在單獨的行上,因爲調用函數打印它,然後打印餘額。如果我改變最後2行

print(printLedgerLine(date,amount,details),str(balance)) 

然後打印無平衡

我是否應該返回printLedgerLine,但是如果我這樣做,我該如何「格式化」它而不打印?令人沮喪,感覺就像它在那裏,我會因爲它的容易程度而感到尷尬! 對不起,長時間混淆的問題,難以解釋什麼時候你的業餘愛好者! 感謝

+0

這樣做'打印(printLedgerLine(日期,金額,細節),STR(平衡))'打印'printLedgetLine',這可能是'None'的返回值。你如何看待printLedgerLine函數?是否僅打印製表符分隔的行或「當前平衡」行?或者只是沒有實際餘額的「當前餘額」? –

+0

歡呼都回答!格式是T所需要的,在此之前我只是在打印它。@tobias_k - printLedgerLine函數最初並沒有涉及餘額,只是在使用存款/提款時才需要它。 –

+0

從'#與項目(和餘額)間隔和格式化'的描述看起來'printLedgerLine'應該總是打印天平,所以它應該是該功能的一部分,而不是「提取」或「存款」 –

回答

1

很難說究竟是什麼錯,沒有看到你的printLedgerLine功能,但是從你的問題似乎只打印日期,具體內容和金額沒有最終的平衡,並打印在depositwithdraw功能的平衡,而不是。

取而代之,您應該將其移至printLedgerLine,並在depositwithdraw中調用該函數。事情是這樣的:

def deposit(date, details, amount): 
    global balance 
    balance = float(balance) + float(amount) 
    printLedgerLine(date,amount,details) 

def printLedgerLine(date,amount,details): 
    print("{}\t{}\t$ {:.02f}\t$ {:.02f}".format(date, details, amount, balance)) 
2

而不是print(printLedgerLine(date,amount,details),str(balance))

你可以做變化printLedgerLine到getLedgerLine並使其返回值,例如

def getLedgerLine(date, amount, details): 
    return '{0}\t{1}\t{2}'.format(date, amount, details) 

然後用

print('{0}\t{1}'.format(printLedgerLine(date,amount,details),str(balance))) 

或者你可以大概取代整個printLedgerLine函數:

def deposit(date, details, amount): 
    global balance 
    balance = float(balance) + float(amount) 
    print('{date}\t{amount}\t{details}\t{balance}'.format(
     date=date, 
     amount=amount, 
     details=details, 
     balance=balance 
    ))