python - 为什么我的 elif 会回到我的 if?

标签 python if-statement python-3.x

我编写了一个非常基本的加密程序,在为其编写解密算法时,我遇到了一些循环问题。

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() 首先将输入转换为固定大小写。

关于python - 为什么我的 elif 会回到我的 if?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13763754/

相关文章:

windows - 在 .cmd 中使用 Windows 命令测试是 32 位还是 64 位并运行命令

python - 如何实现这种运动风格的边界或碰撞?

python - 在 Mac OS X 上安装 libxml2 时出现问题

java - 初学者 Java 项目 : Basic Pokedex using if-else statements. 有建议吗?

python - 在 Python 中,是否可以在一个表达式中将列表拆分为第一个、内部和最后一个元素?

django - 使用 WebSocketCommunicator 在 Django Channels v2 测试中进行身份验证

python-3.x - 如何获得 Tensorflow 中线性回归的正确答案?

Python 或 Powershell — 读取 csv 并排序和收集要在电子邮件中发送的数据

python - 用python卷积周期图像

javascript - 仅在 iPad 上禁用 javascript 代码