Ensure a variable is divisible by 4
Tim Chase
python.list at tim.thechases.com
Mon Dec 4 12:35:42 EST 2006
> I am sure this is a basic math issue, but is there a better way to
> ensure an int variable is divisible by 4 than by doing the following;
>
> x = 111
> x = (x /4) * 4
>
> Just seems a bit clunky to me.
You're right...you'll want to read up on the "modulo" operator:
if x % 4 <> 0:
print "Hey, x isn't divisible by 4"
http://docs.python.org/lib/typesnumeric.html
To do what you describe above, you can also use
x = x - (x % 4)
which isn't greatly better in the clunkiness department. In both
cases, non-divisible-by-4 numbers get bumped down (to the "left"
on the number line) in the event that it's not divisible by 4.
-tkc
More information about the Python-list
mailing list