# [Tutor] Modulus wierdness?

Kent Johnson kent37 at tds.net
Tue Nov 16 02:27:18 CET 2004

```You are re-assigning num, then trying to use its original value again in
the print. Try this:
num2 = min_ord + (num % max_ord)

# this shows really wacky modulus results
print '%i + (%i / %i)[%i] = %i' % (min_ord, num, max_ord, num %
max_ord, num2)
num = num2

David Clymer wrote:
> Just for fun & practice, I'm implementing a character rotation cypher
> (e.g. rot13) script. I'm trying to use modulus to wrap the characters'
> ordinal's around, but I seem to be getting really weird results. When I
> try the operation in a python shell, it all works fine...so I think i'm
> misunderstanding something. Does modulus work diffently on variables
> than it does on literals?
>
> The example script is below.
>
> -davidc
>
> #! /usr/bin/python
>
> import sys
>
> def rot(text,rotation):
>   textchars = list(text)
>   min_ord=32
>   max_ord=126
>
>   index=0
>   for c in textchars:
>     if ord(c) < min_ord or ord(c) > max_ord:
>       continue
>     else:
>       num = ord(c) + rotation
>       print '%i + %i = %i' % (ord(c), rotation, num)
>       if num > max_ord:
>         num = min_ord + (num % max_ord)
>
>         # this shows really wacky modulus results
>         print '%i + (%i / %i)[%i] = %i' % (min_ord, num, max_ord, num %
> max_ord, num2)
>
>       textchars[index] = chr(num)
>
>     index += 1
>
>   return ''.join(textchars)
>
>
> if __name__ == '__main__':
>   if len(sys.argv) > 1:
>     if len(sys.argv) > 2:
>       print rot(sys.argv[1],int(sys.argv[2]))
>     else:
>       print rot(sys.argv[1],13)
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
```