Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I nest single line statements in Python?

A simple question. First off, I've noticed in Python that I can make things more concise by changing short statements like this:

if some_condition:
    do_something()

To this:

if some_condition: do_something()

This change, of course, only works if the code inside the if statement consists of only one line.

However if there is more than one nested "construct" (I'm referring to things like an if-else, for, while, or try-except statement) then I get a syntax error. For example, I can't change this:

if some_condition:
    if other_condition:
        do_something()

To this:

if some_condition: if other_condition: do_something()

Or even this:

if some_condition: if other_condition:
    do_something()

But this does work:

if some_condition:
    if other_condition: do_something()

My guess is that the reason for this is that having two constructs on one line like that creates some kind of ambiguity. I would like to know if there is some way I can still put two statements on a line but have it work. For example, maybe something similar to this:

if some_condition: (if other_condition: do_something())

That, of course, doesn't work. However, hopefully, it makes it a little more clear what exactly I'm trying to do here. Any ideas would be appreciated other than "You shouldn't do this."

Before I get a rush of all you purists out there coming in and preaching how this isn't Pythonic or whatever, YES, I know that this isn't the best way to write code in Python. Consider it a research question. I just want to know if what I'm looking for is possible.

like image 235
Aaron Beaudoin Avatar asked Mar 07 '26 12:03

Aaron Beaudoin


1 Answers

It's impossible to put multiple colons on one line.

Regardless, PEP8 recommends always following a colon with a new line. In most cases, it's best to follow this guideline.

As @Suven Pandey notes, if statements can be nested on one line using nested ternary operators, but please don't use more than one on a single line. At that point, the code is supremely ugly and unreadable.

like image 80
Alec Avatar answered Mar 09 '26 00:03

Alec