混淆 if not elif not 语句冲突

Confused if not elif not statements conflicting

我正在使用 argparse。我正在努力做到这一点,所以如果这些语句没有结合使用,我会收到一条消息说 "Error: Incompatible arguments."

if not args.write == args.write * args.encrypt:
    print("Error: Incompatible arguments.")
    sys.exit()
elif not args.write == args.write * args.encrypt * args.copy:
    print("Error: Incompatible arguments.")
    sys.exit()
else:
    print("The rest of the code..")

这不是预期的结果...

使用 -w -e 给我 "Error: Incompatible arguments." 使用 -w -e -c 正确执行代码。

为什么会这样?我该如何解决?

谢谢。

为什么不在这里做更直观的事情呢?

if (args.write != args.write * args.encrypt) or (args.write != args.write * args.encrypt * args.copy):
    print("Error: Incompatible arguments.")
    sys.exit()
else:
    print("The rest of the code..")

你在向后测试。它应该只设置 writeencrypt 是合法的,但是当 not args.write == args.write * args.encrypt 通过时,它正在移动到 elif,如果 copy0,那么你会说它不兼容,即使它通过了第一个(充分的)有效性测试。

我猜你真的想测试:

if not (args.write == args.write * args.encrypt or args.write == args.write * args.encrypt * args.copy):
    print("Error: Incompatible arguments.")
    sys.exit()

# Equivalent test if it's more clear to distribute the not:
if args.write != args.write * args.encrypt and args.write != args.write * args.encrypt * args.copy:
    ...

这表示如果任一测试为真,则参数正确,而不是说如果任一测试为假,则参数不正确(通过任一测试意味着您有有效参数)。

请注意,如果这些都是 True/False 开关,那么做数学测试是一种愚蠢的测试方法,直接测试您要查找的内容即可:

if args.write and not args.encrypt: # Don't test copy at all, because -w requires -e, but doesn't say anything about -c in your described logic

elif 是不是不必要的,你似乎说要么 -w 没有设置,要么你必须设置 -e 如果 -w 设置有或没有 -c,所以你只需要第一个条件,不是吗?

简化版:

if not args.write == args.write * args.encrypt:
    print("Error: Incompatible arguments.")
    sys.exit()
print("The rest of the code..")

仅使用布尔逻辑:

if args.write and not args.encrypt:
    print("Error: Incompatible arguments.")
    sys.exit(1)
print("The rest of the code..")