spikespaz spikespaz - 4 months ago 7
Python Question

Python: Shorten concatenation by using inline conditionals

If the title is a bit obscure, an example of what I would like to do is:

print("Status: " + if serverIsOnline: "Online" else: "Offline")


I know this is improper, but what I am trying to do is check if
serverIsOnline
is
True
then print
Status: Online
else
Status: Offline
. I know it's possibe, I have seen it done, but I can't remember how it was done.

This is a shorter equivalent of:

if serverIsOnline:
print("Status: Online")
else:
print("Status: Offline")


Could someone please refresh me?

Answer

What you're looking for is a conditional expression (also known as a ternary expression in many other languages, usually with a ? operator used)

print("Status: " + "Online" if serverIsOnline else "Offline")

Syntax: True if condition else False