Reputation: 11
I want to add x
to value
, however when the value
is equal to max_value
, it much wrap back to zero and continue adding the rest of x
.
For example,
x = 5
value = 6
max_value = 8
This should return value = 3
So far I have
value += x
if value >= max_value:
value = value - max_value
However this only works for when value + x
is less than 2 * max_value
.
Upvotes: 0
Views: 280
Reputation: 2398
What you want is modular arithmetic.
You can use the modulo operator %
in Python to achieve this. E.g.
x = 5
value = 6
max_value = 8
value = (value + x) % max_value
The modulo operator (%
) returns the remainder of the integer division of the left side by the right side. See the docs for details.
Upvotes: 4