2017-06-01 17 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

あなたは@Pruneような関数からわずかreturn変数があったはずです。

しかし、場合にあなたは文字通り、それは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の代替案ははるかに優れています。コメント(2回)に記載されているので、私はそれを提示しました。

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クレジット失われた] 魅力のように動作します。

関連する問題