-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
97 lines (71 loc) · 3.02 KB
/
Copy pathmain.py
File metadata and controls
97 lines (71 loc) · 3.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
art = '''
CCCCC AAA EEEEE SSSSS AAA RRRRR
C C A A E S A A R R
C AAAAAAA EEE SSSSS AAAAAAA RRRRR
C A A E S A A R R
CCCCC A A EEEEE SSSSS A A R R
CCCCC IIIII PPPP H H EEEEE RRRR
C I P P H H E R R
C I PPPP HHHHH EEE RRRR
C I P H H E R R
CCCCC IIIII P H H EEEEE R R
'''
print(art)
# List containing all letters of the alphabet.
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def caesar(original_text, shifter, encode_decode):
# Reverse the shift when decoding the message.
if encode_decode == "decode":
shifter *= -1
encrypted_text = ""
# Go through every character in the original message.
for char in original_text:
# Only shift characters that exist in the alphabet.
if char in alphabet:
index = alphabet.index(char) + shifter
# Keep the index inside the alphabet using modulo.
# For example, z shifted by 1 becomes a.
index %= len(alphabet)
encrypted_text = encrypted_text + alphabet[index]
else:
# Keep spaces and other characters unchanged.
encrypted_text += char
print(f"Your {encode_decode} result is :{encrypted_text}")
# Controls whether the program should continue running.
continue_flaged = True
while continue_flaged:
# Ask the user whether they want to encode or decode a message.
direction = input(
"Type 'encode' to encrypt, type 'decode' to decrypt:\n"
).lower()
# Make sure the user entered a valid direction.
if direction != 'encode' and direction != 'decode':
print("please enter right input")
break
else:
# Get the message from the user.
text = input("Type your message:\n").lower()
# Convert the shift value from a string to an integer.
# ValueError occurs if the user enters something that isn't a number.
try:
shift = int(input("Type the shift number:\n"))
except ValueError:
print("Please enter a number")
break
# Encrypt or decrypt the message.
caesar(original_text=text, shifter=shift, encode_decode=direction)
# Ask the user if they want to use the program again.
restart_loop = input(
"Type yes if you want to go again, otherwise type no:\n"
).lower()
# Check if the user entered a valid answer.
if restart_loop == "yes" or restart_loop == "no":
if restart_loop == "yes":
continue_flaged = True
else:
continue_flaged = False
print("Goodbye")
else:
print("please enter yes or no")
continue_flaged = False