【问题标题】:Why am I getting a type error in my code?为什么我的代码中出现类型错误?
【发布时间】:2019-10-25 07:26:39
【问题描述】:

我正在尝试编写 vigenere 密码。我对此的假想是: - 查找明文中每个字母的索引 - 找到关键信息中每个字母的索引 - 将索引加在一起 - 新字母将位于索引总和的位置

我相信我的代码组织正确,但我不确定我是否因为遇到类型错误而遗漏了什么。

# global constants:
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
ALPHABET_SIZE = len(ALPHABET)

# main function definition:
def main():
    # User interface:
    print("Welcome to the Vigenere Cipher!")

    keep_running = True

    while(keep_running):
        print("Enter 1 to encrypt a message")
        print("Enter 2 to decrypt a message")
        print("Enter 0 to exit")
        print()

        user_choice = int(input("What would you like to do? " ))

        if user_choice == 0:
            keep_running = False

        if user_choice == 1:
            plaintext = input("Enter a plaintext message to encrypt: ")
            key = str(input("Enter a message to use as the key: "))
            ciphertext = enc(key, plaintext)
            print("Resulting cipertext:", ciphertext)
            print()


        if user_choice == 2:
            ciphertext = str(input("Enter a ciphertext message to decrypt: "))
            key = str(input("Enter a message to use as the key: "))
            plaintext = dec(key, ciphertext)
            print("Resulting plaintext:", plaintext)
            print()


def enc(key, plaintext):
    ciphertext = []
    for cipher_char in plaintext:
        char_pos = ALPHABET.index(cipher_char)
    for key_char in key:
        message_pos = ALPHABET.index(key_char)
    new_pos = (char_pos + key_char)
    enc_char = ALPHABET(new_pos)
    plaintext += enc_char
    return plaintext






# call to main:
main()

【问题讨论】:

  • 您忘了告诉我们是哪一行出错了?
  • 不要使用while keep_running:,这是一种反模式。使用while True:,然后使用break 停止循环。
  • ALPHABET(new_pos) 无效。 ALPHABET 是一个字符串,而不是一个函数。我怀疑你的意思是ALPHABET[new_pos]。您还需要处理 new_pos 太大,并将其包裹起来。

标签: python encryption vigenere


【解决方案1】:

错误在这一行

new_pos = (char_pos + key_char)

char_pos 是一个位置,是 int 类型。 key_char 是一个字符并且是字符串类型。您不能将一个添加到另一个。

也直接在上面的这些行中:

    for cipher_char in plaintext:
        char_pos = ALPHABET.index(cipher_char)
    for key_char in key:
        message_pos = ALPHABET.index(key_char)

每个 for 循环都一遍又一遍地设置变量(分别为 char_pos 和 message_pos)。因此,仅考虑字母表中每个字符串(分别为明文和键)中最后一个字符的位置。所以你需要重新思考一下逻辑。

最后我建议您在 ALPHABET 中包含大写字符。第一次尝试时出现值错误,因为我尝试了大写输入。

【讨论】:

  • 你应该解释如何修复坏线。 key_char 应该是 message_pos
  • 这是真的,但仍然不会使代码工作。还有其他问题需要解决,所以我决定只回答这个问题。希望ajn多花点时间思考和学习。
  • 感谢您的帮助!!!我对此很陌生,所以我非常感谢关于做什么等方面的建议。
猜你喜欢
  • 2021-10-18
  • 2020-03-25
  • 1970-01-01
  • 1970-01-01
  • 2022-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多