【发布时间】:2022-01-19 03:21:15
【问题描述】:
下面的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)
上面的代码执行了一个控制台,打印功能被执行了两次。对于编码和解码,打印功能有两个答案。为什么我的代码会遇到这个问题?
【问题讨论】:
-
我没有从您提供的代码中得到任何双重打印。但是,请注意,在您的第一个
for循环中,您将在每次迭代时覆盖encoded_text的值,并将其重置为空字符串。 -
我无法重现该问题。请发送minimal reproducible example。你可以edit。顺便说一句,欢迎来到 Stack Overflow!请拨打tour,并查看How to Ask 了解更多提示。
-
如果您提供了几个具体的输入和输出示例,帮助您会容易得多。例如,如果您的输入只有一两个字母,那么下一个问题将是“如果您输入更长的输入会发生什么”?如果结果是更多的打印,那将是一个关于哪里出了问题的巨大线索。