I want to add a number y to x, but have x wrap around to remain between zero and 48. Note y could be negative but will never have a magnitude greater than 48. Is there a better way of doing this than:
x = x + y
if x >= 48:
x = x - 48
elif x < 0:
x = x + 48
?
The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem. The modulo operator is considered an arithmetic operation, along with + , - , / , * , ** , // . The basic syntax is: a % b.
Now here we are going to discuss a new type of addition, which is known as “addition modulo m” and written in the form a+mb, where a and b belong to an integer and m is any fixed positive integer. By definition we have. a+mb=r,for0⩽r<m.
The Python modulo operator calculates the remainder of dividing two values. This operator is represented by the percentage sign (%). The syntax for the modulo operator is: number1 % number2. The first number is divided by the second then the remainder is returned.
Wouldn't just (x+ y)% 48
be suitable for you. See more on modulo here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With