[Tutor] Modulus Operator ?

Alan Gauld alan.gauld at btinternet.com
Thu Nov 19 19:25:42 EST 2015


On 19/11/15 21:11, Ken Hammer wrote:
> ...The 2nd below mystifies me.  How do I use "x % 10"  and "x % 100"
...
> 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).

> I understand these:
>
> x = 49/13
> print x
> 3
 >
 > y = 49%13
 > print y
 > 10

So now try it with 10 instead of 13

print 49%10
9

> z = 0.0 + x + y/13.0
> print z
> 3.76923076923
>
> print 49.0/13
> 3.76923076923

Since mod doesn't come into these you can't really apply it.

But here is another example, lets create a list of numbers:

 >>> nums = [123,234,345]

Now we want the last two digits from each number,
so we use mod 100:

 >>> for n in nums:
...   print n % 100
23
34
45


As always in python the best way to see how something
works is just to try it out at the >>> prompt.
If something gives a different result to what you
expect then come back here and ask.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list