2017-06-01 94 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信用损失] 工程就像一个魅力。