Неверный синтаксис с использованием оператора + = - PullRequest
2 голосов
/ 06 мая 2020

Я постоянно получаю синтаксическую ошибку при использовании + = в python вот мой код. У меня тоже проблемы с нелокальным. Я получаю много ошибок, включая синтаксические ошибки и несвязанную локальную ошибку. Заранее спасибо !!!

обновление: добавлен дополнительный код, это весь код Теперь говорится, что локальная переменная «граждане» упоминалась перед назначением

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

Ответы [ 2 ]

3 голосов
/ 06 мая 2020

Три вещи с этим кодом:

  1. присвоение rnum не удастся, потому что вы не выполняете целочисленное деление
  2. На самом деле вы хотите global, а не non-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   

Хотя я бы порекомендовал вообще избегать нелокальности, поскольку в будущем это может вызвать множество ошибок. Я бы предложил стилистически сделать что-то вроде этого:

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

Здесь это хорошая статья и хорошее видео о том, как работает прицел в python, но хорошее практическое правило - просто хранить все, что вы можете, локально.

0 голосов
/ 06 мая 2020

Проблема в том, что nonlocal citizens должен быть на отдельной строке. Попробуйте это:

import random
rd = random.randint
citizens = rd(10000, 1000000)
def function():
   rnum = rd(1,citizens/2)
   nonlocal citizens
   citizens -= rnum
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...