[Tutor] Checksum program

Tom Zych freethinker at pobox.com
Wed Mar 23 15:19:14 CET 2011

Lezlie Kline wrote:

> I'm trying to work out the bugs in a program for calculating the checksum
> (modulo 256) of an input string.  I'm testing it with my full name and I'm a
> beginner with Python.  Here's what I have so far.
> def main():
>     print"This program creates a checksum for a message."
>     name=raw_input("Please enter the message to encode: ")
>     message=name
>     output=name
>     for i in range(len(message)):
>         print"The value of message[i] is ", message[i]
>         output=output+name+ord(message[i])
>         print"The value of the message is ", output
>     checksum=(output)%256
>     print"The checksum is ", checksum
> main()

You're not too far off.  Take a good look at everything you do with
`output`.  In particular, note what type of object it is.

Your loop will work but it's not Pythonic - you can iterate over a
sequence directly:

    for i in message:
        # i = a character (string of length 1) from message
        print "Processing", i

Tom Zych / freethinker at pobox.com
"Because if they didn't vote for a lizard," said Ford, "the wrong lizard
might get in." -- DNA

More information about the Tutor mailing list