litigious.formalism
litigious.formalism

Reputation: 31

One line Conditional constructs in python

In javascript, I could make one-line conditional constructs, like:

var Verbose = true; // false
if ( Verbose ) console.log("Verbose mode");

In shell scripting ( bash ), I could make one-line conditional constructs, like:

Verbose=false # true
[ $Verbose == true ] && echo "Verbose mode" || echo "Silent mode"

How can I make the same in python?

This is necessary for wrapping "verbose" messages in big and deep recursion methods. I can wrap it by function or use two lines, like:

if Verbose:
         print "Verbose mode"

But this is looks too ugly.

Upvotes: 0

Views: 646

Answers (3)

Ryan Haining
Ryan Haining

Reputation: 36802

The other answers have covered

if verbose: print 'Verbose'

but for your middle example needing an else, you could use a ternary

print 'Verbose' if verbose else 'Silent'

Though the stylistic merits of this are... questionable

Upvotes: 2

AChampion
AChampion

Reputation: 30258

As pointed out you can put the if and print on a single line.
But just for completeness and an awful use of python short circuiting you can write:

verbose = True
verbose and print("Verbose mode")

But this is ugly. You can even achieve the equivalent of your bash statement

verbose and not print("Verbose mode") or print("Silent mode")

But this is even uglier :)

Upvotes: 3

Alex Martelli
Alex Martelli

Reputation: 881675

Python lets you have if and guarded statement on a single line:

if verbose: print('verbose')

PEP 8 discourages this, as a matter of style; but Python still allows it (and will forever:-) and I personally don't mind it when the guarded statement is short and structural (such as break, continue, &c)

Upvotes: 3

Related Questions