👇알파벳을 이용한 암호화 복호화 코드
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곱하는건 생각도 못했다.
이번에 배웠다.
반응형
'언어 > 파이썬' 카테고리의 다른 글
[부트캠프] 간단한 계산 프로그램 만들기 - 10일 (0) | 2023.05.22 |
---|---|
[부트캠프]Dictionary 딕셔너리 -9일차 (1) | 2023.05.17 |
[부트캠프] for 과 while 반복문 - 6일차 (0) | 2023.05.05 |
[부트캠프] for문으로 비밀번호 만들기 (0) | 2023.05.03 |
[부트캠프] random 함수와 배열 활용 (0) | 2023.05.01 |