Python: elif or new if?

后端 未结 5 757
谎友^
谎友^ 2021-01-04 21:52

What is better to use:

if var in X:
    #do_whatever
elif (var in Y):
    #do_whatever2

or:

if var in X:
    #do_whatever
i         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-01-04 22:25

    If you need to perform both checks, you should use two separate ifs. If you want to check one or the order you should always use elif because

    • It's more efficient. You will save resources if your first condition is true.
    • You can have unexpected errors if both conditions are true.

    Performance wise, you should also consider testing the most likely condition first.

提交回复
热议问题