Python/If

Aus Shea Wiki
Zur Navigation springen Zur Suche springen

Python: if statements, several ways

For this example, we will consider adult people over 18, otherwise, are children.

1) Basic way

Option A

if age >= 18:
  typeOfPerson = "adult"
else:
  typeOfPerson = "child"

We can assign a default value and change it only if a condition is met.

Option B

typeOfPerson = "child" #default value
if age >= 18:
  typeOfPerson = "adult"

Option A is better than option B for code optimization, assuming that the probability of either is not very far (Thanks to Arturo Moysen for this comment).

2) Inline if (result = x if condition else y)

typeOfPerson = "adult" if age >= 18 else "child"

3) Inline if (result = condition and x or y)

typeOfPerson = age >= 18 and "adult" or "child"

4) Inline with tuple, (on_false, on_true)[condition]

typeOfPerson = ("child", "adult")[age >= 18]

Condition can be anything that evaluates to a Boolean. It is then treated as an integer since it is used to index the tuple: False == 0, True == 1, which then selects the right item from the tuple.


KategorieWissen