[英]Why am I getting a type error in my code?
我正在嘗試編寫一個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()
錯誤在這一行
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中包含大寫字母。 第一次嘗試時出現值錯誤,因為嘗試了大寫輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.