Python全局变量balance报错:赋值前引用/全局声明前置问题
Python全局变量错误修复:取款后更新余额的问题
嘿,我来帮你搞定这个全局变量的问题!你遇到的报错根源很明确:在函数里修改全局变量时,必须在第一次使用该变量之前就声明global。
你的service()函数里,先在if amount > balance:这行使用了balance变量,之后才在取款成功的分支里声明global balance,这就触发了"name 'balance' is used prior to global declaration"的错误——Python会认为你先想用局部变量balance,之后又突然说它是全局的,逻辑冲突了。
修复方案
只需要在service()函数的最开头就声明global balance,这样函数内所有对balance的读取和修改都会指向全局定义的那个变量。
修正后的完整代码
pin = input("Set your PIN: ") balance = 1000 wrong = 1 def service(): global balance # 提前声明,确保函数内所有balance操作都指向全局变量 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: new_balance = balance - amount print(f"You withdraw: {amount} from your account and your current balance is: {new_balance} $") balance = new_balance service() elif nextt == 2: print("Thank you for your visit // exiting...") return elif nextt == 3: print(f"Your current balance is: {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 += 1 if wrong > 3: print("\n You reached the max. amount to enter your PIN correctly, exiting...") return else: card() card()
关键修改点说明
- 提前声明全局变量:在
service()函数第一行就加上global balance,这样函数内所有地方用到的balance都是全局变量,不管是读取(比如判断余额是否足够)还是修改(取款后更新余额)都不会有问题。 - (可选优化)我把字符串拼接改成了f-string,让代码更简洁易读,功能和原来完全一致。
- 把
wrong = wrong + 1改成了wrong += 1,这是Python里更简洁的写法。
现在你运行代码试试:设置PIN后,输入正确PIN进入服务,取款后再查询余额,就能看到余额已经正确更新啦!
内容的提问来源于stack exchange,提问作者lorde
相关产品推荐
相关产品推荐

