Subscribe Contact

Home  »  Chapter 3 : Decisions
In-line if (a.k.a. Ternary) Statements

Overview

The in-line if statement evaluates one or more conditions and returns an output. The in-line if is also known as the Ternary Operator.

General Form

The general form of the inline if (Ternary Operator) statement looks like this:

[true_result] if [condition(s)] else [false_result][None]
Notice that the entire statement is on one line. Here's how it works:
  • [true_result]: This is the expression that will be evaluated and returned if the [condition] is true.
  • [condition]: This is (are) the boolean condition(s) that the ternary operator checks and that drives the result.
  • [false_result]: This is the expression that will be evaluated and returned if the [condition] is false.
  • [None]: There is no direct equivalent of the simple if statement (thst is, an if with no else clause) in the inline if statement. So, to represent the simple if in ternary, we must include else None instead.

Forms of In-Line if Statements

We saw on previous pages in this chapter that decisions are written as if, if-else, and if-elif-else statements. We can write these decisions structures as in-line if statements as well. Here is table that compares the structures side-by-side.

Form Traditional Syntax In-Line Syntax
if
x = 10
y = 20
if x > y:
    print("x is greater than y")
'''
NOTE: There is no direct equivalent of the simple if statement
(that is, an if with no else clause) in the inline if statement.
So, to represent the simple if in ternary, we must include
else None (as shown below) instead.
'''
x = 10
y = 20
print("x is greater than y") if x > y else None
if-else
x = 10
y = 20
if x > y:
    print("x is greater than y")
else:
    print("x is not greater than y")
x = 10
y = 20
print("x is greater than y") if x > y else print("x is not greater than y")
if-elif-else
x = 10
y = 20
if x > y:
    print("x is greater than y")
elif x < y:
    print("x is less than y")
else:
    print("x equals y")
x = 10
y = 20
print("x is greater than y") if x > y else (print("x is less than y") if x < y else print("x equals y"))


Practice Problems

Problem 1

Write an inline if statement that prints "Yes" if a variable (x) equals 10.




Problem 2

Write an inline if statement that prints "Yes" if a variable (x) equals 10 or "No" if the variable does not equal 10.




Problem 3

Write an inline if statement that prints "Even" if the value of a variable contains an even number, or prints "Odd" if the value is odd.




«  Previous : Decisions : if-elif-else Statements
Next : Repetition   »




© 2023 John Gordon
Cascade Street Publishing, LLC