Although a single line circuit

Is it possible to have python in a loop on only one line, I tried this:

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

But it gives an error message: Invalid Syntaxin statementif

+5
source share
3 answers

When using the compound operator in Python (operators that need to be typed, an indented block), and this block contains only simple operators , you can remove the newline character and separate the simple operators with a semicolon.

However, this does not support compound statements.

So:

if expression: print "something"

works but

while expression: if expression: print "something"

not because the operators whileand ifare integral.

if expression: assignment , :

while expression: target = true_expression if test_expression else false_expression

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

, , , .

+10

/ , . , , , .. , :

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

" n rn, , 0".

+4

- :

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

Source: https://habr.com/ru/post/1543427/


All Articles