Issue
The below python code is my project on caesar cipher
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', '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']
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
def caesar(plain_text,shift_num,direction):
if direction == "encode":
encoded_text = ''
for letter in plain_text:
encoded_text = ''
encoded_text += alphabet[alphabet.index(letter)+shift_num]
print(f"the encoded text is {encoded_text}")
elif direction == "decode":
decoded_text = ''
for letter in plain_text:
decoded_text += alphabet[alphabet.index(letter)-shift_num]
print(f"the decoded text is {decoded_text}")
caesar(plain_text = text,shift_num = shift,direction=direction)
The above code performs a console where the print function is performed twice. for both encode and decode the print function has two answers. Why do i encounter this problem in my code?
Solution
Here you go:-
The improved version. I imported string so you don’t have to make an alphabet list.
import string
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
def caesar(plain_text,shift_num,direction):
e_msg = ""
if direction == "encode":
for i in plain_text:
if not i == " ":
e_msg += string.ascii_lowercase[(string.ascii_lowercase.index(i) + shift) % 26]
else:
e_msg += " "
print(e_msg)
elif direction == "decode":
for i in plain_text:
if not i == " ":
e_msg += string.ascii_lowercase[(string.ascii_lowercase.index(i) - shift) % 26]
else:
e_msg += " "
print(e_msg)
caesar(plain_text = text,shift_num = shift,direction=direction)
Answered By – Pranav
Answer Checked By – Gilberto Lyons (BugsFixing Admin)