Skip to content

How to put multiple statements in one line?

I wasn’t sure under what title to ponder this question exactly, coding golf seems appropriate if a bit unspecific.

I know a little bit of comprehensions in python but they seem very hard to ‘read’. The way I see it, a comprehension might accomplish the same as the following code:

for i in range(10): if i == 9: print('i equals 9')

This code is much easier to read than how comprehensions currently work but I’ve noticed you cant have two : in one line … this brings me too…

my question:

Is there any way I can get the following example into ONE LINE?

    if sam[0] != 'harry':
        print('hello',  sam)

Something like this would be great:

try: if sam[0] != 'harry': print('hellp',  sam)

But again I encounter the conflicting : I’d also love to know if there’s a way to run try (or something like it) without except, it seems entirely pointless that I need to put except:pass in there. its a wasted line.



Unfortunately, what you want is not possible with Python (which makes Python close to useless for command-line one-liner programs). Even explicit use of parentheses does not avoid the syntax exception. You can get away with a sequence of simple statements, separated by semi-colon:

for i in range(10): print "foo"; print "bar"

But as soon as you add a construct that introduces an indented block (like if), you need the line break. Also,

for i in range(10): print "i equals 9" if i==9 else None

is legal and might approximate what you want.

As for the try ... except thing: It would be totally useless without the except. try says “I want to run this code, but it might throw an exception”. If you don’t care about the exception, leave away the try. But as soon as you put it in, you’re saying “I want to handle a potential exception”. The pass then says you wish to not handle it specifically. But that means your code will continue running, which it wouldn’t otherwise.

5 People found this is helpful