Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c819ea4

Browse files
Update CaesarCipher.py
1 parent b153374 commit c819ea4

File tree

1 file changed

+56
-2
lines changed

1 file changed

+56
-2
lines changed

‎CaesarCipher.py

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,60 @@
11
# 1. Receive a message and then encrypt it by shifting the
22
# characters by a requested amount to the right.
33

4-
# A becomes D, B becomes E, for example. Also
5-
# decrypt the message back.
4+
# A becomes D, B becomes E, for example. Also, decrypt the message back.
65

6+
# HINTS
7+
8+
# 1. A-Z have the numbers 65-90 in unicode
9+
# 2. a-z have the numbers 97-122
10+
# 3. You get the unicode of a character with ord(yourLetter)
11+
# 4. You covert from unicode to character with chr(yourNumber)
12+
# 5. Use isupper() to decide which unicode to work with
13+
# 6. Add the key (number of characters to shift)... if bigger or smaller then
14+
# the unicode for A, Z, a, or z increase or decrease by 26
15+
16+
message = input("Enter your message: ")
17+
key = int(input("How many characters should we shift (1-26): "))
18+
secret_message = ""
19+
20+
for char in message:
21+
if char.isalpha():
22+
char_code = ord(char) + key
23+
24+
if char.isupper():
25+
if char_code > ord("Z"):
26+
char_code -= 26
27+
elif char_code < ord("A"):
28+
char_code += 26
29+
else:
30+
if char_code > ord("z"):
31+
char_code -= 26
32+
elif char_code < ord("a"):
33+
char_code += 26
34+
secret_message += chr(char_code)
35+
else:
36+
secret_message += char
37+
print("Encrypted:", secret_message)
38+
39+
original_message = ""
40+
key = -key
41+
42+
for char in secret_message:
43+
if char.isalpha():
44+
char_code = ord(char) + key
45+
46+
if char.isupper():
47+
if char_code > ord("Z"):
48+
char_code -= 26
49+
elif char_code < ord("A"):
50+
char_code += 26
51+
else:
52+
if char_code > ord("z"):
53+
char_code -= 26
54+
elif char_code < ord("a"):
55+
char_code += 26
56+
original_message += chr(char_code)
57+
else:
58+
original_message += char
59+
60+
print("Decrypted: ", original_message)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /