""" cipher_functions.py Using our earlier crypto example as a demonstration of functions and doctests. This is my recommended model for simple programming in python. Jim M | Oct 2013 """ def encode_char(character, key): """ Given a lowercase character, return it shifted upward by the key. >>> encode_char('a', 3) # three characters after 'a' 'd' >>> encode_char('z', 2) # wrap around 'b' """ ascii_value = ord(character) # e.g. 97 for 'a' zero_to_25 = ascii_value - ord('a') # e.g. 0 for 'a' crypt_0_to_25 = (zero_to_25 + key) % 26 # e.g. 0+3 for key=3 crypt_ascii = ord('a') + crypt_0_to_25 # e.g. 100 crypt_char = chr(crypt_ascii) # e.g. 'd' return crypt_char def encode_word(word, key): """ Return the lowercase word shifted upward by the key. >>> encode_word("cat", 3) # c shifts to f, a to d, t to 2 'fdw' >>> encode_word("zoo", 5) '?' """ crypt_word = "" for char in word: crypt_word = crypt_word + encode_char(char, key) return crypt_word def main(): print "-- cipher ---\n" key = int(raw_input("What is the key? (13) ")) plain_text = raw_input("What is the lowercase word? (cat) ") crypt_text = encode_word(plain_text, key) print "'{}' encrypted is '{}'".format(plain_text, crypt_text) if __name__ == "__main__": # invoked as "python cipher_functions.py" ? import doctest doctest.testmod() # Run all the tests. (Do nothing if OK.) main() # Run the main() program.