首页 > 解决方案 > 变量在函数中不起作用(python 3)

问题描述

tokens = 100

def double_or_nothing(amount):
  if randint(1, 0) == 1:
    if input("double? ").lower == "yes":
      amount *= 2
      double_or_nothing(amount)
    else:
      tokens += amount
  else:
    tokens -= amount

我收到一个关于“tokens += amount”的错误,上面写着:[pyflakes] local variable 'tokens' defined in enclosure scope on line 41 referenced before assignment

标签: pythonfunctionvariables

解决方案


您不能修改位于函数之外的变量 - 您可以读取它,但不能修改它。

最干净的解决方案是返回数字标记的变化,而不是操作位于函数外部的变量,然后在函数本身之外跟踪当前标记的数量:

from random import randint
tokens = 100

def double_or_nothing(amount):
  if randint(0, 2) == 1:
    if input("double? ").strip().lower() == "yes":
      amount *= 2
      return double_or_nothing(amount)
    else:
      return amount
  else:
    return -amount

while tokens > 0:
  print("You have ", tokens)
  tokens += double_or_nothing(10)

推荐阅读