使用+=操作符的无效语法

问题描述 投票:0回答:1

当我在python中使用+=时,我一直得到一个语法错误,这里是我的代码。我也有麻烦与非本地。我得到了很多错误,包括语法错误和未绑定的本地错误Thanks in advance!!!

更新:更多的代码添加这是所有的代码它现在说本地变量'公民'引用之前的赋值

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()

python python-3.x random operators
1个回答
3
投票

这段代码有三个问题。

  1. rnum赋值会失败 因为你没有进行整数除法运算
  2. 你其实是想 globalnon-local 在这种情况下,你应该避免使用全局变量。虽然你应该避免使用全局变量这样的方式。
  3. 你可以把第二行作为第一行的一部分来做。

这将是我认为你想要的。

from random import randint as rd
citizens = rd(10000, 1000000)
def function():
  global citizens  # Tells python you want the global value
  rnum = rd(1,citizens//2) # Uses the global value since python knows to do that
  citizens -= rnum   

不过我建议完全避免使用非本地的,因为这可能会导致很多bug 我建议在风格上做这样的事情。

from random import randint as rd
citizens = rd(10000, 1000000) # Initialize citizens to a random value

def reduce_citizens(citizens:int) -> int:
    """Reduces the number of citizens by up to half of the current amount"""
    rnum = rd(1,citizens//2)
    citizens -= rnum   # Since the value is being passed into the function directly we don't need global
    return citizens # give the new value back so it can be used

citizens = reduce_citizens(citizens) # Take the current value of citizens and remove some then reassign to citizens

上面的代码有一个好处,就是可以用在多组公民身上,比如说:

from random import randint as rd
citizens = rd(10000, 1000000)   # Initialize citizens to a random value
citizens_2 = rd(10000, 1000000) # Initialize a second set of citizens to a random value
citizens_3 = rd(10000, 1000000) # Initialize a third set of citizens to a random value

def reduce_citizens(citizens:int) -> int:
    """Reduces the number of citizens by up to half of the current amount"""
    rnum = rd(1,citizens//2)
    citizens -= rnum
    return citizens

citizens = reduce_citizens(citizens) # Take the current value of citizens and remove some then reassign to citizens
citizens_2 = reduce_citizens(citizens) # Take the current value of citizens_2 and remove some then reassign to citizens
citizens_3 = reduce_citizens(citizens) # Take the current value of citizens_3 and remove some then reassign to citizens

这里有一篇不错的文章 和a 好视频 关于 scope 在 python 中的工作原理,但一个很好的经验法则是把所有你能想到的东西都放在本地。


0
投票

问题是 nonlocal citizens 必须在另一行。试试这个。

import random
rd = random.randint
citizens = rd(10000, 1000000)
def function():
   rnum = rd(1,citizens/2)
   nonlocal citizens
   citizens -= rnum
© www.soinside.com 2019 - 2024. All rights reserved.