While loop one-liner

ε祈祈猫儿з 提交于 2019-12-28 18:09:25

问题


Is it possible for to have a python while loop purely on one line, I've tried this:

while n<1000:if n%3==0 or n%5==0:rn+=n

But it produces an error message: Invalid Syntax at the if statement


回答1:


When using a compound statement in python (statements that need a suite, an indented block), and that block contains only simple statements, you can remove the newline, and separate the simple statements with semicolons.

However, that does not support compound statements.

So:

if expression: print "something"

works, but

while expression: if expression: print "something"

does not because both the while and if statements are compound.

For your specific example, you can replace the if expression: assignment part with a conditional expression, so by using an expression instead of a complex statement:

while expression: target = true_expression if test_expression else false_expression

in general, or while n<1000: rn += n if not (n % 3 and n % 5) else 0 specifically.

From a style perspective, you generally want to leave that one line on it's own, though.




回答2:


In your example, you try to collapse two levels of blocks / indentation into a single line, which is not allowed. You can only do this with simple statements, not loops, if statements, function definitions etc. That said, for your example there is a workaround using the ternary operator:

while n < 1000: rn += n if (n % 3 == 0 or n % 5 == 0) else 0

which reads as 'add n to rn if the condition holds, else add 0'.




回答3:


It is posible to do something similar:

rn = 100
for n in range(10): rn += n if (n%3==0 or n%5==0) else 0


来源:https://stackoverflow.com/questions/15185746/while-loop-one-liner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!