【问题标题】:why does the print function command twice? [closed]为什么打印功能命令两次? [关闭]
【发布时间】: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 了解更多提示。
  • 如果您提供了几个具体的输入和输出示例,帮助您会容易得多。例如,如果您的输入只有一两个字母,那么下一个问题将是“如果您输入更长的输入会发生什么”?如果结果是更多的打印,那将是一个关于哪里出了问题的巨大线索。

标签: python string function


【解决方案1】:

给你:- 改进版。我导入了字符串,因此您不必制作字母列表。

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)

【讨论】:

  • 并没有真正回答这个问题。只是显示了另一种编码方式。还添加了原始文件中未显示的细节(处理空格字符)。没有被要求,所以对我来说似乎没有目的。顺便说一句,查找“即兴创作”的定义。
  • 感谢您告诉我英语中的“即兴”错误。在我的辩护中,我是一个 14 岁的孩子,来自一个甚至没有英语作为主要语言的国家。
  • 我认为这不是您的母语 :) 恭喜您的回答被提问者接受!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 2015-04-21
  • 1970-01-01
  • 2022-11-21
相关资源
最近更新 更多