首页 > 解决方案 > 在全局声明之前使用名称“余额”

问题描述

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

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

标签: pythonpython-3.x

解决方案


上面几行,你隐式地通知 Python 这balance是一个局部变量:

if amount > balance:

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

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


推荐阅读