【发布时间】: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