困惑,如果不是elif没有声明冲突

时间:2015-09-18 20:45:25

标签: python if-statement argparse

我正在使用argparse。我试图这样做,如果这些语句没有结合使用,我会收到一条消息“错误:不兼容的参数”。

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给我“错误:不兼容的参数。” 使用-w -e -c可以正确执行代码。

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

谢谢。

3 个答案:

答案 0 :(得分:1)

你正在倒退。它应该是合法的,只有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

答案 1 :(得分:0)

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

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..")

答案 2 :(得分:0)

不是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..")