在我的for循环末尾没有打印多字母cyph的文本

2024-05-28 19:08:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个多胺基密码。我的代码正在运行,但它没有在最后打印“cyphertext”。我甚至试过测试for循环的各个部分,但都不会打印出来

import string

alpha = string.ascii_lowercase

message = input('Message:')
message = message.upper()

secretWord = input('Secret word:')
secretWord = secretWord.upper()

cypherText = ''

count = 0
for letter in message:
  if letter in alpha:
    shift = alpha.index(secretWord[count])
    letterIndex = alpha.index(letter)
    cypherLetter = alpha[(letterIndex+shift)%26]
    cypherText = cypherText + cypherLetter
count = count+1

print(cypherText)

Tags: inalphamessageforinputstringindexshift
3条回答

在代码中的任何地方都使用大写或小写:

import string

alpha = string.ascii_lowercase
message = input('Message: ').lower()
secret_word = input('Secret word: ').lower()
cypher_text = ''
for i, letter in enumerate(message):
    if letter in alpha:
        shift = alpha.index(secret_word[i]) if len(secret_word) > i else alpha.index(secret_word[0])
        letter_index = alpha.index(letter)
        cypher_letter = alpha[(letter_index + shift) % 26]
        cypher_text = cypher_text + cypher_letter
print(cypher_text)

输出:

Message: animal
Secret word: snake
saiwed

您的消息是大写的,但是alpha是小写的,所以您在消息上迭代的字母永远不会出现在alpha

您还在循环外增加计数,这会导致常量偏移

将每个字符都设为大写,然后检查是否为小写字符。因为大写字符不是小写字符,所以它不会被加密

相关问题 更多 >

    热门问题