Test/Python(20220101~)
Day8_Caesar 암호 2단계, decode
kiostory
2022. 1. 10. 20:36
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']
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"))
#TODO-1: Create a function called 'encrypt' that takes the 'text' and 'shift' as inputs.
def encrypt(from_text, amount_shift):
# input_txt=list(from_text)
# for i in range(0,len(input_txt)): #입력 테스트 하나씩 확인
# if input_txt[i] in alphabet and ((alphabet.index(input_txt[i]))+amount_shift) <= 26:
# input_txt[i] = alphabet[(alphabet.index(input_txt[i]))+amount_shift]
# elif input_txt[i] in alphabet and ((alphabet.index(input_txt[i]))+amount_shift) > 26:
# input_txt[i] = alphabet[((alphabet.index(input_txt[i]))+amount_shift)%26]
cipher_text=''
for char in from_text: #입력 테스트 하나씩 확인
if char in alphabet and ((alphabet.index(char))+amount_shift) <= 25:
cipher_text += alphabet[(alphabet.index(char))+amount_shift]
elif char in alphabet and ((alphabet.index(char))+amount_shift) > 25:
cipher_text += alphabet[((alphabet.index(char))+amount_shift)%26]
else:
cipher_text += char
#print(f"The encoded text is \'{''.join(input_txt)}\'")
print(f"The encoded text is \'{cipher_text}\'")
#TODO-2: Inside the 'decrypt' function, shift each letter of the 'text' *backwards* in the alphabet by the shift amount and print the decrypted text.
#e.g.
#cipher_text = "mjqqt"
#shift = 5
#plain_text = "hello"
#print output: "The decoded text is hello"
def decrypt(from_cipher_text, amount_shift):
plain_text=''
for char in from_cipher_text: #입력 테스트 하나씩 확인
if char in alphabet and ((alphabet.index(char))-amount_shift) >= 0:
plain_text += alphabet[(alphabet.index(char))-amount_shift]
elif char in alphabet and ((alphabet.index(char))-amount_shift) < 0:
plain_text += alphabet[((alphabet.index(char))-amount_shift)%26]
else:
plain_text += char
#print(f"The decoded text is \'{''.join(input_txt)}\'")
print(f"The decoded text is \'{plain_text}\'")
if direction == "encode" :
encrypt(text, shift)
elif direction == "decode" :
decrypt(text, shift)
else :
print("Error! Type 'encode' to encrypt, type 'decode' to decrypt.")
#TODO-3: Call the encrypt function and pass in the user inputs. You should be able to test the code and encrypt a message.