spikespaz spikespaz - 1 year ago 81
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download