Три вещи с этим кодом:
- присвоение rnum не удастся, потому что вы не выполняете целочисленное деление
- На самом деле вы хотите
global
, а не non-local
в этом случае. Хотя вам следует избегать использования таких глобальных переменных. - Вы можете сделать вторую строку как часть первой
Я думаю, это именно то, что вам нужно:
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, но хорошее практическое правило - просто хранить все, что вы можете, локально.