gpt4 book ai didi

python - 修复 UnboundLocalError

转载 作者:行者123 更新时间:2023-11-30 22:11:55 25 4
gpt4 key购买 nike

def main():
cash = float(input("How much money: "))
coins = 0

def changeCounter(n):
while True:
if cash - n > 0:
cash -= n
coins += 1
else:
break
return

main()
changeCounter(0.25)

当我运行此代码时,出现错误

UnboundLocalError: local variable 'cash' referenced before assignment

我该如何解决这个问题?

最佳答案

问题在于变量 cashcoins只生活在函数的“范围”内 main ,即在 changeCounter 中不可见。尝试:

def main():
cash = float(input("How much money: "))
coins = 0
return cash, coins

def changeCounter(n, cash, coins):
while True:
if cash - n > 0:
cash -= n
coins += 1
else:
break
# return
return coins # presumably

cash, coins = main()
changeCounter(0.25, cash, coins)

关于python - 修复 UnboundLocalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51279618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com