python - 在全局声明之前使用名称“余额”
问题描述
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
我要做的就是:在那里提取一些现金后更新当前余额!
解决方案
上面几行,你隐式地通知 Python 这balance
是一个局部变量:
if amount > balance:
在这个名称空间(函数范围)中之前没有见过它,所以它是一个局部变量。当你进入这个else
子句时,你突然给 Python 跳了一段“我撒谎”的小舞,宣布它是全球性的。Python 不喜欢这种滑稽动作。
如果您想balance
成为全局变量(不好的做法),请按照编码指南中的建议在块的顶部声明它。更好的是,将其作为函数参数传入,并在完成后返回。
推荐阅读
- javascript - 使用 Prisma、Urql 和 React 加载更多分页?
- r - RLang:通过链接和映射访问列表项(purrr)
- javascript - Postman Web 版本中的“无法发送请求”错误
- r - 将行转置为相应的列
- apple-login - 苹果登录中的无效响应时间
- android - 无法为我的 Android 应用创建 ID 值资源
- flutter - 为什么 App Engine 提供非默认版本?
- java - IntelliJ Exe 构建没有像我预期的那样工作
- pyaudio - 实时音频移调器(Python)
- html - 如何在 JQuery 中从父级访问另一个子类?