我编写了一个非常基本的加密程序,在为其编写解密算法时,我遇到了一些循环问题。
from re import *
cipher = open('cipher.txt')
ciphertext = cipher.read()
keyfile = open('key.txt')
key = keyfile.read()
decoded = []
chardec = ''
inval = 1
print("Decoder for encrypt1.py")
while inval == 1:
useManKey = input("Use a manual key? Y or N\n> ")
if useManKey == 'Y' or 'y':
key = input("Please enter the key you wish to use to decrypt\n> ")
inval = 0
elif useManKey == 'N' or 'n':
inval = 0
print("OK, decrypting")
else:
print("That wasn't a valid option/nPlease re-enter")
当我运行它,并将 useManKey 声明为 N 或 n 时,它似乎运行循环的 if 部分,就好像我将其声明为 Y 或 y 一样。我在这里可能很愚蠢,但非常感谢任何帮助。
请您参考如下方法:
useManKey == 'Y' or 'y' 并不像您想象的那样工作。你想要的是 useManKey in ('Y', 'y')。您首先评估 useManKey == 'Y',然后,如果该检查失败,则测试字符串 'y' 的真实性。由于非空字符串始终为真,因此您的 if 语句的计算结果始终为 True。正如评论中指出的那样,如果需要,您还可以使用 upper() 或 lower() 首先将输入转换为固定大小写。
