Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

if statement - Python if test condition fails when used with or

Greetings python experts. I had written an if condition as follows that fails to be false for objects that should be false. I am writing in python 3.8.5. Note instance_list in this example contains a list of resources that are in various states. I only want to append vm_instance_list with resources that are not in a TERMINATED or TERMINATING state.

instance_results = compute_client.list_instances(
    compartment_id = compartment_id).data
vm_instance_list = []
for instance in instance_results:
    if instance.lifecycle_state != "TERMINATED" or instance.lifecycle_state != "TERMINATING:
        vm_instance_list.append(instance)

The above code appends vm_instance_list with every object in the list instance_results, aka each condition is interpreted as True for objects that are in a TERMINATED or TERMINATING lifecycle state. I have had to re-write to nest the if conditions, which works.

for instance in instance_results:
    if instance.lifecycle_state != "TERMINATED:
        if instance.lifecycle_state != "TERMINATING":
            vm_instance_list.append(instance)

I have no idea what why I have had to nest the above if statements and would appreciate if anyone could share some insights.

Thanks so much,

  • Hank
question from:https://stackoverflow.com/questions/65948714/python-if-test-condition-fails-when-used-with-or

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your first version, the result is ALWAYS true, so every item is appended. Your second version is only true if both tests are true.

If you want the first version to behave like the second version, you need an 'and' statement, not an 'or'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...