Test/Python(20220101~)
Day8_Caesar 암호 1단계, encoding
kiostory
2022. 1. 9. 21:48
# encode 를 선택하고, 텍스트 메세지를 입력한 후 shift할 양을 넣으면,
# shift되어 암호화 된 텍스트가 출력된다.
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, from_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]))+from_shift) <= 26:
# input_txt[i] = alphabet[(alphabet.index(input_txt[i]))+from_shift]
# elif input_txt[i] in alphabet and ((alphabet.index(input_txt[i]))+from_shift) > 26:
# input_txt[i] = alphabet[((alphabet.index(input_txt[i]))+from_shift)%26]
cipher_text=''
for char in from_text: #입력 테스트 하나씩 확인
if char in alphabet and ((alphabet.index(char))+from_shift) <= 25:
cipher_text += alphabet[(alphabet.index(char))+from_shift]
elif char in alphabet and ((alphabet.index(char))+from_shift) > 25: # shift해서 알파벳 z를 넘게 되면 a부터로 되돌아가게 %나머지 계산을 생각하게 되었음
cipher_text += alphabet[((alphabet.index(char))+from_shift)%26]
else:
cipher_text += char
#print(f"The encoded text is \'{''.join(input_txt)}\'")
print(f"The encoded text is \'{cipher_text}\'")
encrypt(text,shift)
#TODO-2: Inside the 'encrypt' function, shift each letter of the 'text' forwards in the alphabet by the shift amount and print the encrypted text.
#e.g.
#plain_text = "hello"
#shift = 5
#cipher_text = "mjqqt"
#print output: "The encoded text is mjqqt"
##HINT: How do you get the index of an item in a list:
#https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list
##?Bug alert: What happens if you try to encode the word 'civilization'??
#TODO-3: Call the encrypt function and pass in the user inputs. You should be able to test the code and encrypt a message.