0

In a tutorial for developing a processing-plugin for QGIS I found the following Python3-code:

  # Compute the number of steps to display within the progress bar and
  # get features from source
  total = 100.0 / source.featureCount() if source.featureCount() else 0
  features = source.getFeatures()

My question: What kind of language construct is this single line:

total = 100.0 / source.featureCount() if source.featureCount() else 0

This looks weird: Frist an assignment , which is followed by an if-else-construct in the same line??

Kurt
  • 264
  • 1
  • 7
  • 23
  • 2
    Does this answer your question? [Putting a simple if-then-else statement on one line](https://stackoverflow.com/questions/2802726/putting-a-simple-if-then-else-statement-on-one-line) – Carcigenicate Aug 03 '21 at 14:24
  • 2
    These are called ["conditional expressions"](https://docs.python.org/3/reference/expressions.html#conditional-expressions). From the linked documentation: "The expression `x if C else y` first evaluates the condition, `C` rather than `x`. If `C` is true, `x` is evaluated and its value is returned; otherwise, `y` is evaluated and its value is returned." – zr0gravity7 Aug 03 '21 at 14:26
  • 1
    thanks for your answers. Lesson learned. @zr0gravity7 if you post an short answer I can checkmark it – Kurt Aug 03 '21 at 15:42

1 Answers1

1

These are called "conditional expressions". From the Python 3 reference:

The expression x if C else y first evaluates the condition, C rather than x. If C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

You can read it as "return x if C otherwise return y."

When a conditional expression is used in the assignment to a variable, that variable will take on the value returned by that conditional expression.

This concept is usually referred to as a "ternary" in many other languages.

zr0gravity7
  • 2,917
  • 1
  • 12
  • 33