Search code examples
pythonrenpy

Limit randomly modified number to not go past a specified max


I have a variable that increases by randomly chosen values (this is for a game) - the increases varies from 0.25 up to 1.5. That is working fine.

When that variable reaches a specific number (or above), it turns another variable from False to True.

However, I'm displaying this variable as a percentage of the total (total being 150, so it will show something like 5.5% / 150, 15% of 150 and so on).

What I would like to be able to do, is stop the variable from going past the max - ie, if I have the variable at 149, and I increase it by 1.5, it will end up at 150.5. I would like to stop it at 150.

Is there a way in Python that will accomplish this?

I guess I could just do a check every time the counter increases, and if it goes past 150, I can just modify it to set it to 150, but I was wondering if there is a method, or modifier I can use to do this while increasing the value of the variable itself.


Solution

  • Using the min keyword is the best way I know.

    variable = min(variable + 1.5, 150)