While循环忽略If语句

时间:2020-05-03 17:41:07

标签: python

我正在生成“键值”,这将有助于功能加密和解密完成其工作。

'if ans == e'语句正在运行,并且确实返回输出,但忽略了'k = True'语句,导致程序在加密函数上陷入无限循环。有人知道它为什么这样做吗?

ans = input("Would you like to decrypt or encrypt your message (e/d)? ")
key = Generate.gen.keys(self)

k = False
while not k:

    if ans == "e":
        encrypt(key[0], key[1])
        k = True

    if ans == "d":
        decrypt(key[0], key[2])
        k = True

    else:
        k = False


def encrypt(n, e):
    output = []
    plain_text = input("Please enter message: ")
    raw = list(plain_text)
    print(raw)

    for char in raw:
        ascii_val = ord(char)
        pub = ascii_val ** e % n
        print(pub)
        output.append(pub)
    print(output)

非常感谢, 卡勒姆

2 个答案:

答案 0 :(得分:3)

if ans == "e":
    encrypt(key[0], key[1])
    k = True
if ans == "d":
    decrypt(key[0], key[2])
    k = True  
else:
    k = False

如果您阅读代码,则其逻辑如下。

  1. 如果ans =='e'设置k = true
  2. 如果ans =='d'设置k = true
    1. 如果ans!='d'设置k = false

如果ans =='e'为true,则ans无法=='d',因此运行else情况,将k设置为false。

考虑为ans =='d'使用elif elif ans == 'd':

答案 1 :(得分:0)

k = False
while not k:
    if ans == "e":
        # ...
        k = True

如果ans == "e"为真,则k = True确实将被执行。

但是,接下来的if / else语句到来了。

    if ans == "d":
        # ...
    else:
        k = False

如果ans"e",则不会同时是"d"。因此,将执行else部分,它将k设置回False

您需要使用elif ans == "d"以便跳过此部分if ans == "e"之前是真的。