view raw
spikespaz spikespaz - 9 months ago 29
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
then print
Status: Online
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")
print("Status: Offline")

Could someone please refresh me?


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