且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在一行中放置多个语句?

更新时间:2022-06-22 22:03:16

不幸的是,Python 无法实现您想要的(这使得 Python 对于命令行单行程序几乎毫无用处).即使显式使用括号也不能避免语法异常.您可以使用以分号分隔的一系列简单语句:

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"

但是,一旦您添加了一个引入缩进块的构造(如 if),您就需要换行符.还有,

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.

至于 try ... except 事情:没有 except 将完全没用.try 说我想运行这段代码,但它可能会抛出异常".如果您不关心异常,请不要使用 try.但是一旦你把它放进去,你就会说我想处理一个潜在的异常".pass 然后表示您不希望专门处理它.但这意味着您的代码将继续运行,否则就不会.

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.