Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inline if else?

Here is part of code. I need to understand what this code do :

if instruction == "JOINT" or instruction == "ROOT":
    parent = joint_stack[-1] if instruction == "JOINT" else None
    joint = BvhJoint(words[1], parent)
    self.joints[joint.name] = joint

How to understand this line special ->

    parent = joint_stack[-1] if instruction == "JOINT" else None

Is this code equal with JS code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if (instruction == "JOINT") {
    parent = joint_stack[-1];
} else {

}

?

>Solution :

The equivalent JS code would be:

   if (instruction == "JOINT") { 
        parent = joint_stack[-1];
    } else {
        parent = null;
    }

or more idiomatically:

    parent = instruction == "JOINT" ? joint_stack[-1] : null;

This ternary expression in Python:

joint_stack[-1] if instruction == "JOINT" else None

is the same as the JS ternary expression:

instruction == "JOINT" ? joint_stack[-1] : null
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading