Optimized way to check and update many variables at once if the condition is the same – PYTHON

Question:

i’m beginner in Python and i’m trying to do a game. This part of the code works fine as it is, but i’m pretty sure that there’s a more elegant way to do the same thing.

Basically if a variable reaches above 100, the value will be 100. If the value is lower than 0, the value will be 0. (like a limit)

if economy >= 100:
    economy = 100
if economy <= 0:
    economy = 0
if population >= 100:
    population = 100
if population <= 0:
    population = 0
if religion >= 100:
    religion = 100
if religion <0:
    religion = 0

As I said, the code works, but I’m pretty sure that there’s a optimized way to do this since the condition is the same.

Asked By: muryllo

||

Answers:

Slightly open-ended question, you could look into one-line if statements as a possibility, and somewhere within your entire program, make sure that the values can not go below 0. That would look something like

company = 100 if company >= 100 else company
economy = 100 if economy >= 100 else economy

However, this does not necessarily solve your problem much. Uploading your entire program may prove to be useful

Answered By: Michael Gathara
if economy >= 100:
    economy = 100
if economy <= 0:
    economy = 0
if population >= 100:
    population = 100
if population <= 0:
    population = 0
if religion >= 100:
    religion = 100
if religion <0:
    religion = 0

can be rewritten as

economy = max(0, min(100, economy))
population = max(0, min(100, population))
religion  = max(0, min(100, religion))

First you take the minimum of 100 and x. If x >= 100, then you get 100, otherwise you get x.

Suppose y = min(100, x). Then you take the maximum of y and 0. If y <= 0, you get 0. Otherwise, you get y.

You could make this even more concise by generalizing the code. For example, could you hold all of the values you’re counting in a list or dictionary? Then you could do something like this:

for i in range(counts):
    counts[i] = max(0, min(100, counts[i])

or

ECONOMY_KEY = "ECONOMY"
POPULATION_KEY = "POPULATION"
RELIGION_KEY = "RELIGION"

keys = [ECONOMY_KEY, POPULATION_KEY, RELIGION_KEY]

...

for key in keys:
    counts[key] = max(0, min(100, counts[key])
Answered By: J.R.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.