大家好,我是新的自学者。我尝试编写“Caeser Cipher”的代码

问题描述 投票:0回答:1

进口艺术品 字母表 = ['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'] 印刷品(艺术标志)

def caeser(纯文本,shift_num): 密文 = "" 对于纯文本中的字符: 如果字符在字母表中: pos = alphabet.index(字符) 新位置 = 0 如果方向==“编码”: new_pos = pos + shift_num 如果 new_pos == 26: new_pos_x = 0 new_letter = 字母表[new_pos_x] 密文+=新字母 elif new_pos > 26: new_pos_z = new_pos - 26 new_letter = 字母表[new_pos_z] 密文+=新字母 别的: new_letter = 字母表[new_pos] 密文+=新字母

elif 方向 == “解码”: new_pos = pos - shift_num new_letter = 字母表[new_pos] 密文+=新字母 别的: 密文 += 字符 print(f"{direction}d 文本是 {cipher_text}")

continue_q = 真 而 continue_q:

direction = input("输入'encode'进行加密,输入'decode'进行解密: “)。降低() text = input("请输入您的信息: “)。降低() shift = int(input("请输入班次编号: “)) 如果班次 >= 26: 移位 = (移位 % 26) caeser(plain_text = text, shift_num = shift)

result = input("如果您想继续,请输入“是”。否则请输入“否”。 “)。降低() 如果结果 == “否”: continue_q = 假 打印(“Ciao :)”)

#如果用户输入除“encode”或“decode”之外的任何其他关键字,是否有循环此代码的方法。

python caesar-cipher
1个回答
0
投票

是的,您可以使用 while 循环重复提示用户输入有效输入,直到他们输入“编码”或“解码”。这是一个示例实现:

代码:

import art

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']

print(art.logo)

def caesar(plain_text, shift_num, direction):
    cipher_text = ""
    for char in plain_text:
        if char in alphabet:
            pos = alphabet.index(char)
            if direction == "encode":
                new_pos = pos + shift_num
                if new_pos >= 26:
                    new_pos = new_pos - 26
                new_letter = alphabet[new_pos]
                cipher_text += new_letter
            elif direction == "decode":
                new_pos = pos - shift_num
                new_letter = alphabet[new_pos]
                cipher_text += new_letter
        else:
            cipher_text += char
    print(f"The {direction}d text is {cipher_text}")

continue_q = True
while continue_q:
    direction = ""
    while direction != "encode" and direction != "decode":
        direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower()
    text = input("Type your message:\n").lower()
    shift = int(input("Type the shift number:\n"))
    shift = shift % 26
    caesar(plain_text=text, shift_num=shift, direction=direction)
    result = input("Type 'Yes' if you want to continue. Else Type 'No'.\n").lower()
    if result == "no":
        continue_q = False
print("Ciao :)")

在这个实现中,外层的while循环用于重复加密或解密过程,直到用户选择退出。内部 while 循环用于重复提示用户输入“编码”或“解码”,直到他们输入有效输入为止。如果用户输入任何其他关键字,循环将继续,直到他们输入有效的输入。

© www.soinside.com 2019 - 2024. All rights reserved.