【问题标题】:name 'balance' is used prior to global declaration在全局声明之前使用名称“余额”
【发布时间】:2018-10-21 05:53:51
【问题描述】:
pin = input("Set your PIN: ")
balance = 1000
wrong = 1

def service():
  nextt = int(input("\nWelcome! \n Press 1 - to withdraw some money and \n 
                    Press 2 - to exit the service \n Press 3 - to show 
                    current balance \n "))
  if nextt == 1:
    amount = int(input("\nHow much money do you want: "))
    if amount > balance:
      print("Sorry, but your current balance is only: " +str(balance)+" $")
      service()
    else:
      print("You withdraw: " +str(amount) +" from your account and your 
             current balance is: " +str(balance-amount)+" $")
      global balance
      balance -= amount
      service()
  elif nextt == 2:
    print("Thank you for your visit // exiting...")
    return
  elif nextt == 3:
    print("Your current balance is: " +str(balance)+" $")
    service()
  else:
    print("\n Failure: Press 1 to withdraw some money, 2 to exit the service 
          and 3 to show current balance!")
    service()

def card():
  global wrong
  choose = input("\nEnter your card PIN: ")
  if choose == pin:
    service()
  else:
    print("\n You entered the wrong PIN!")
    wrong = wrong + 1
    if wrong > 3:
      print("\n You reached the max. amount to enter your PIN correctly, 
            exiting...")
      return
    else:
      card()


card()

我无法修复这个特殊错误:

on line 14: balance -= amount 

我想在提取一些现金后更新余额,但它说:

  local variable 'balance' referenced before assignment

我加了

  global balance 
  balance -= amount

新错误:

name 'balance' is used prior to global declaration

我要做的就是:在那里提取一些现金后更新当前余额!

【问题讨论】:

  • 为什么不将global balance 移动到函数定义的顶部(而不是将其埋在else 子句中)?
  • 你说的对,我是说看卡片功能,全局错误,我做对了,搞砸了服务功能 OMG xD

标签: python python-3.x


【解决方案1】:

上面几行,你隐含地告诉 Python balance 是一个局部变量:

if amount > balance:

在这个命名空间(函数作用域)中之前没有见过它,所以它是一个局部变量。当你进入else 子句时,你突然给 Python 跳了一段“我撒谎”的小舞,宣布它是全球性的。 Python 不喜欢这种滑稽动作。

如果您希望 balance 成为全局变量(不好的做法),请按照编码指南中的建议在块的顶部声明它。更好的是,将其作为函数参数传入并在完成后返回。

【讨论】:

    【解决方案2】:

    有时准确列出正在运行的代码很方便:

    nextt = int(input("\nWelcome! ..."))  # "nextt" is being set in the local scope
    if nextt == 1:                        # "nextt" is being compared to 1
        amount = int(input("\nHow ..."))  # "amount" is being set in the local scope
        if amount > balance:              # "amount" is being compared to "balance"
                                          # Uh oh! We haven't defined "balance" yet!
            print("Sorry, ...")
            ...
    

    要解决此问题,您可以使用global 关键字,它会在全局范围内查找变量。在找到解决方案之前,让我们看一个例子来说明它是如何工作的:

    def f1():
        a = 2
        print("Value of a: {}; ID of a: {}".format(a, id(a)))
    
    def f2():
        global a
        print("[Before] Value of a: {}; ID of a: {}".format(a, id(a)))
        a = 3
        print("[After] Value of a: {}; ID of a: {}".format(a, id(a)))
    
    >>> a = 1  # we define "a" in the global scope
    
    >>> a, id(a)  # id(variable) gets a unique value for this variable
    (1, 1635934432)
    
    >>> f1()
    Value of a: 2; ID of a: 1635934464  # So you see that the ID is different, because this is f1's version of "a", not the global one
    
    >>> a, id(a)
    (1, 1635934432)  # the value and ID of the global variable remain unchanged
    
    >>> f2()
    [Before] Value of a: 1; ID of a: 1635934432  # see the value and ID of the local "a" are now the same as the global variable
    [After] Value of a: 3; ID of a: 1635934496  # we replaced the value and ID here
    
    >>> a, id(a)
    (3, 1635934496)  # which has affected the global version now as well
    

    最后,完整的解决方案:

    global balance                        # "balance" is set to the global value
    nextt = int(input("\nWelcome! ..."))  # "nextt" is being set
    if nextt == 1:                        # "nextt" is being compared to 1
        amount = int(input("\nHow much ...: "))  # "amount" is being set
        if amount > balance:              # "amount" is being compared to "balance"
            print("Sorry, ...")
            ...
    

    【讨论】:

      【解决方案3】:

      简单的解决方法(如果您坚持使用全局变量)是将全局语句重新定位到 def service 函数中的第一条语句:

      def service():
         global balance
      

      您的代码非常随意地使用全局变量,这是一个坏主意。已经提出了其他建议来纠正这个问题,所以我不会进一步扩展:)

      【讨论】:

        猜你喜欢
        • 2011-01-07
        • 2016-04-23
        • 2023-01-07
        • 2020-06-02
        • 1970-01-01
        • 1970-01-01
        • 2019-04-18
        • 2017-05-16
        • 1970-01-01
        相关资源
        最近更新 更多