簡體   English   中英

如果不是elif not語句沖突,則會感到困惑

[英]Confused if not elif not statements conflicting

我正在使用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可以正確執行代碼。

為什么會這樣呢? 我該如何解決?

謝謝。

您正在向后測試。 應該只設置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

為什么不在這里做更直觀的事情?

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

elif並不是不必要的,您似乎說-w沒有設置,或者-e是否設置了-c都必須設置-e,所以只需要第一個條件,不是嗎?

簡化:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM