Python 修复未绑定的LocalError
当我运行这段代码时,我得到了错误 UnboundLocalError:分配前引用的局部变量“cash”Python 修复未绑定的LocalError,python,Python,当我运行这段代码时,我得到了错误 UnboundLocalError:分配前引用的局部变量“cash” 如何解决此问题?您需要将现金和硬币定义为: 但比将状态存储在全局变量中更好的方法是使用 返回变量和函数参数或其他方法。看见 问题在于,变量现金和硬币仅存在于函数main的“范围”内,即在兑换计数器中不可见。尝试: cash = 0 coins = 0 def main(): global cash, coins cash = float(input("How much m
如何解决此问题?您需要将
现金和硬币定义为:
但比将状态存储在全局变量中更好的方法是使用
返回变量和函数参数或其他方法。看见
问题在于,变量现金
和硬币
仅存在于函数main
的“范围”内,即在兑换计数器
中不可见。尝试:
cash = 0
coins = 0
def main():
global cash, coins
cash = float(input("How much money: "))
coins = 0
def changeCounter(n):
global cash, coins
while True:
if cash - n > 0:
cash -= n
coins += 1
else:
break
return
main()
changeCounter(0.25)
那么你也需要将硬币
作为全球货币。如果你将现金作为全球货币,那么你也应该将硬币作为全球货币。可能是
cash = 0
coins = 0
def main():
global cash, coins
cash = float(input("How much money: "))
coins = 0
def changeCounter(n):
global cash, coins
while True:
if cash - n > 0:
cash -= n
coins += 1
else:
break
return
main()
changeCounter(0.25)
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)