Jacob Birkett
Jacob Birkett

Reputation: 2125

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?

Upvotes: 0

Views: 94

Answers (2)

ospahiu
ospahiu

Reputation: 3525

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

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

Syntax: True if condition else False

Upvotes: 3

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18467

Python allows inline if/else as long as an else is specified (if only is a SyntaxError). Most Python programmers refer to this as its ternary:

>>> server_online = True
>>> print('Status: ' + ('Online' if server_online else 'Offline'))
Status: Online
>>> server_online = False
>>> print('Status: ' + ('Online' if server_online else 'Offline'))
Status: Offline
>>> print('Status: ' + 'Online' if server_online)
  File "<stdin>", line 1
    print('Status: ' + 'Online' if server_online)
                                                ^
SyntaxError: invalid syntax

Upvotes: 1

Related Questions