在函数外部使变量可用

时间:2017-06-01 00:04:12

标签: python python-3.x function variables

我有以下代码:

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)

现在我需要能够阅读变量&#34; credit&#34;在主代码中,但我收到错误

  

NameError:name&#39; credit&#39;未定义

如何从函数credit中提取变量Payment以在主程序中使用?

4 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

你应该{@ 1}}来自@Prune这个函数的变量显示。

但是如果你真的想要它作为global变量,你必须在函数外部定义它并在函数内使用return(这将告诉Python它应该改变函数范围之外的变量):

global credit

但是使用credit = 0 def Payment(): global credit credit = float(input()) while credit < 1: newcredit = float(input()) credit = newcredit + credit Payment() print(credit) 的替代方案要好得多,我只是提出它,因为它在评论中提到过(两次)。

答案 2 :(得分:0)

除了返还信用额外,您还可以将该值存储到另一个变量中并以此方式处理。如果您需要进一步修改该信用变量。 new_variable = credit print(new_variable)

答案 3 :(得分: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 :''的费用为1英镑    CON :请插入硬币
  :0.5
   CON :您的信用现在为100英镑    CON :您还需要再增加0.5美分!   :49.5
  可变“信用”更新为付款(100)=&gt; 50
   CON :50

[50学分= 100学分减50学分丢失] 像魅力一样。