2017-06-01 95 views
-1

我有以下代碼:使其可用的功能外變量

def Payment(): 
    print('The cost for''is 1£') 
    print('Please insert coin') 
    credit = float(input()) 
    while credit < 1: 
     print('Your credit now is', credit,'£') 
     print('You still need to add other',-credit+1,'cent') 
     newcredit = float(input()) 
     credit = newcredit + credit 
Payment() 
print(credit) 

現在我需要的是能夠同時在主代碼後讀變量「信用」,但我得到的錯誤

NameError: name 'credit' is not defined

如何從函數Payment中提取變量credit以在主程序中使用?

+0

您可以嘗試使用'global credit'作爲全局變量傳遞它。 –

回答

3

返回它作爲功能結果:

def Payment(): 

    print('The cost for''is 1£') 
    print('Please insert coin') 
    credit = float(input()) 

    while credit < 1: 
     print('Your credit now is', credit,'£') 
     print('You still need to add other',-credit+1,'cent') 
     newcredit = float(input()) 
     credit = newcredit + credit 

    return credit 


balance = Payment() 
print(balance) 
+0

還可以聲明信用爲全局變量,雖然這不是真正的好作風 –

+2

我清楚這一點 - 無論它是可能的,而且它的不良作風。教他們路徑...... :-) – Prune

1

你應該只從return像@Prune功能的變量顯示。

,但如果你硬是想把它當作global變量,你必須定義它的功能之外,它global credit你的函數內部(即會告訴Python的,應該改變功能範圍之外的變量):

credit = 0 

def Payment(): 
    global credit 
    credit = float(input()) 
    while credit < 1: 
     newcredit = float(input()) 
     credit = newcredit + credit 
Payment() 
print(credit) 

return的替代方案好得多,我只是提出它,因爲它在評論(兩次)中提到。

0

除了返回貸方之外,您可以將該值存儲到另一個變量中並以此方式處理。如果您需要進一步修改信用變量。 new_variable = credit print(new_variable)

0

這比你想象的更容易。
首先,分配一個名爲credit的變量(在函數外)。這不會與任何功能交互。

credit = 0 

讓你的函數除了增加一個參數和增加一個return語句。

def Payment(currentcredit): 
     ... 
     return currentcredit - credit #lose credit after payment 

最後,

credit = Payment(credit) 

最後的代碼是

credit = 100 
def Payment(currentcredit): 
    print('The cost for''is 1£') 
    print('Please insert a coin') 
    credit = float(input()) 
    while credit < 1: 
     print('Your credit is now', currentcredit,'£') 
     print('You still need to add another',-credit+1,'cents!') 
     newcredit = float(input()) 
     credit = newcredit + credit 
    return currentcredit - credit 
credit = Payment(credit) 
print(credit) 

輸出

CON: The cost for ' ' is 1£
CON: Please insert a coin
ME: 0.5
CON: Your credit is now 100£
CON: You still need to add another 0.5 cents!
ME: 49.5
Variable "credit" updated to Payment(100) => 50
CON: 50

[50信用= 100信用減去50信用損失] 工程就像一個魅力。