Sean
Sean

Reputation: 3385

Is writing an if statement on one line acceptable?

I'm not sure if this question is appropriate for this community since it's more opinion-oriented, so please vote to close it if it's not.

My question is regarding the if statement in Python (perhaps not just Python either) and the style. Is it acceptable to write it in one line? I'm not talking about the ternary operator of the form something if condition else something-else but rather when people write:

if condition: do this

rather than

if condition:
    do this

I'm confused because I was always taught (and personally believe it's better) to write conditionals in the second form. However, I've noticed that many people write it in the first form.

In what cases would this be acceptable? I couldn't find a particular guideline on this topic online.

Upvotes: 0

Views: 1615

Answers (2)

Sid
Sid

Reputation: 2189

This is discouraged, but acceptable. Either way works and is executed without any errors.

Upvotes: 1

iz_
iz_

Reputation: 16593

PEP 8 (scroll down a bit), the style guide for Python, discourages this:

Compound statements (multiple statements on the same line) are generally discouraged.

Yes:

if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

Rather not:

if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

Upvotes: 1

Related Questions