[Tutor] Modulus wierdness?

David Clymer david at zettazebra.com
Tue Nov 16 02:10:29 CET 2004

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.


#! /usr/bin/python

import sys

def rot(text,rotation):
  textchars = list(text)

  for c in textchars:
    if ord(c) < min_ord or ord(c) > max_ord:
      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]))
      print rot(sys.argv[1],13)

More information about the Tutor mailing list