Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 51 lines (38 sloc) 1.473 kb
f16b361 @asweigart Initial commit.
authored
1 # Caesar Cipher
2 # http://inventwithpython.com/codebreaker (BSD Licensed)
3
4 # the string to be encrypted/decrypted
5 message = 'This is my secret message.'
6
7 # the encryption/decryption key
8 key = 13
9
10 # tells the program to encrypt of decrypt
11 mode = 'encrypt' # set to 'encrypt' or 'decrypt'
12
13 # every possible symbol that can be encrypted
14 SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
15
16 # stores the encrypted/decrypted form of the message
17 translated = ''
18
19 # capitalize the string in message
20 message = message.upper()
21
22 # run the encryption/decryption code on each symbol in the message string
23 for symbol in message:
24 # get the number of the symbol
25 num = SYMBOLS.find(symbol)
26
27 # -1 means the symbol in the message was not found in SYMBOLS
28 if num != -1:
29 # get the encrypted (or decrypted) number for this symbol
30 if mode == 'encrypt':
31 num = num + key
32 elif mode == 'decrypt':
33 num = num - key
34
35 # handle the wrap around if num is larger than the length of SYMBOLS
36 # or less than 0
37 if num >= len(SYMBOLS):
38 num = num - len(SYMBOLS)
39 elif num < 0:
40 num = num + len(SYMBOLS)
41
42 # add encrypted/decrypted number's symbol at the end of translated
43 translated = translated + SYMBOLS[num]
44
45 else:
46 # just add the symbol without encrypting/decrypting
47 translated = translated + symbol
48
49 # print the encrypted/decrypted string to the screen
50 print(translated)
Something went wrong with that request. Please try again.