Skip to content
Advertisement

How can I put multiple statements in one line?

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 can’t have two :s in one line. This brings me to:

Is there a way I can get the following example into one line?

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

Something like this would be great:

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

But again I encounter the conflicting :s.

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. It’s a wasted line.

Advertisement

Answer

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 semicolon:

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.

If you are still determined to use one-liners, see the answer by elecprog.

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 out 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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement