Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

python - While loop one-liner

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...