首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么打印函数要命令两次?

为什么打印函数要命令两次?
EN

Stack Overflow用户
提问于 2022-01-19 03:21:15
回答 1查看 58关注 0票数 0

下面的python代码是我关于凯撒密码的项目。

代码语言:javascript
运行
复制
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)

上面的代码执行一个控制台,其中打印函数执行两次。对于编码和解码,打印函数有两个答案。为什么我在代码中遇到这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-19 03:48:37

给你:-改良版。我导入了字符串,这样你就不用做字母表列表了。

代码语言:javascript
运行
复制
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)
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70764959

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档