언어/파이썬

[부트캠프] shift를 이용한 암호화 복호화 코드 8일차

앨리스.W 2023. 5. 9. 20:38

👇알파벳을 이용한 암호화 복호화 코드

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'
]


def caesar(start_text, shift_amount, cipher_direction):
    end_text = ""
    #decode일때만 -1
    if cipher_direction == "decode":
        shift_amount *= -1
    for char in start_text:
        #특수문자나 숫자를 입력하더라도 배열에 있는 값만 변환
        if char in alphabet:
            new_position = alphabet.index(char) + shift_amount
            end_text += alphabet[new_position]
        else:
            end_text += char
    print(f"{cipher_direction}: {end_text}")


#계속해서 프로그램을 진행 할것인지 확인
end_flag = False
while not end_flag:

    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"))
    # 만약 26이상의 숫자를 입력시 26으로 나누어서 값을 구함
    shift = shift % 26

    caesar(text, shift, direction)

    restart = input(
        "Type 'yes' if you want to go again. Otherwise type 'no'.\n")
    if restart != "yes":
        end_flag = True
        print("Goodbye")

  후기

특히 나누셈으로 순서를 다시구하는 것과 'decode'일때 -1곱하는건 생각도 못했다.

이번에 배웠다. 

반응형