下面的python代码是我关于凯撒密码的项目。
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)上面的代码执行一个控制台,其中打印函数执行两次。对于编码和解码,打印函数有两个答案。为什么我在代码中遇到这个问题?
发布于 2022-01-19 03:48:37
给你:-改良版。我导入了字符串,这样你就不用做字母表列表了。
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)https://stackoverflow.com/questions/70764959
复制相似问题