【问题标题】:Make the variable available outside the function使变量在函数外可用
【发布时间】:2017-06-01 00:04:11
【问题描述】:

我有以下代码:

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)

现在我需要能够在主代码中的 while 之后读取变量“credit”,但我得到了错误

NameError: name 'credit' 未定义

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

【问题讨论】:

  • 您可以尝试使用 global credit 将其作为全局变量传递。

标签: python python-3.x function variables


【解决方案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

    return credit


balance = Payment()
print(balance)

【讨论】:

  • 你也可以将 credit 声明为一个全局变量,虽然这不是很好的风格
  • 我很清楚这一点——既是可能的,又是不好的风格。教他们路径... :-)
【解决方案2】:

你应该只是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 的替代方案要好得多,我只是介绍了它,因为它在 cmets 中提到过(两次)。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      这比您想象的要容易。
      首先,分配一个名为 credit 的变量(函数外)。这不会与任何函数交互。

      credit = 0
      

      让你的函数除了添加参数和返回语句之外。

          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:请投入硬币
      ME:0.5CON:您的积分现在是 100 英镑
      CON:您还需要再加 0.5 美分!
      ME: 49.5
      变量“信用”更新为 Payment(100) => 50
      CON:50

      [50 积分 = 100 积分减去 50 积分损失] 像魅力一样工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-05
        • 1970-01-01
        • 1970-01-01
        • 2018-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多