【发布时间】:2020-08-21 16:42:38
【问题描述】:
在 python 中使用 += 时,我不断收到语法错误 这是我的代码。我也有非本地的麻烦。 我收到很多错误,包括语法错误和未绑定的本地错误 先谢谢了!!!
更新:添加了更多代码 这是所有的代码 现在说 赋值前引用的局部变量“citizens”
from time import sleep as slp
import time
import sys
def clear():
print("\033[2J\033[H", end="")
def slow(text, endl="\n"):
for c in text:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
print(endl, end="")
def slow_in(prompt=''):
slow(prompt, endl="")
return input()
import random
def generate():
import random
slow("generating random circumstance...")
slp(2)
slow("done")
rd = random.randint
money = rd(1, 100)
health = 100
global citizens
citizens = rd(10000, 1000000)
supporters = rd(1,1000000)
def show():
print("money-" + str(money))
print("health-" + str(health))
print("citizens-" + str(citizens))
print("suppporters-" + str(supporters))
waysod = [""]
def death():
wod = random.choice(waysod)
rnum = rd(1,citizens//2)
citizens -= rnum
print(str(rnum) + " citizens died " + wod)
return citizens
import random
rd = random.randint
slow("Welcome to presidential nightmare! ")
from time import sleep as slp
slp(.6)
slow("The easiest thing to do in this game is, well...")
slp(.8)
slow("destroy the country!!")
slp(.6)
slow("lets get started!!!")
slp(.6)
slow_in("press enter to continue...")
generate()
show()
death()
【问题讨论】:
-
去掉
nonlocal关键字,你没有正确使用它,这里不需要它。 stackoverflow.com/questions/1261875/python-nonlocal-statement -
nonlocal 仅在嵌套范围内有效,并且必须在自己的行中。
-
你的 death() 函数需要带一个参数。考虑这一点的最简单方法是,每个功能都是一个房子,当你在房子里时,你不能和房子外面的人交谈,所以你需要把他们带进去。因此,在您的情况下,您需要执行 def death(citizens): # Put code in here 此外,最好在 cmets 中提出后续问题或在堆栈溢出上发布新帖子,因为我发布的答案对这段代码不再有意义。
标签: python python-3.x operators python-nonlocal