Another
very important operator called Modulus operator which works on integers and
yields the remainder when the first operand is divided by the second. In Python
as in most programming languages the modulus operator is a percent sign (%).
The syntax is the same as for other operators.
>>> quo = 10/3 >>>print quo 3 >>>remainder = 10 % 3 >>>print remainder 1
In
previous example 10 divide by 3 is 3 with 1 left over.
The
actual result can be computed in following way.
>>>10/3.0 3.3333333333333335
The
modulus operator turns out to be very useful. You can check whether one number
is divisible by another. If x%y is zero than x is divisible by y.
Also,
you can extract the right-most digit or digits from a number. For example, x %
10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the
last two digits.
>>>5%10 5 >>>5 / 10.0 0.5 >>>x = 50 >>>x % 100 50 >>>50 / 100.0 0.5
Nema komentara:
Objavi komentar