While loop one-liner

后端 未结 3 1740
星月不相逢
星月不相逢 2020-12-10 16:14

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 produ

3条回答
  •  春和景丽
    2020-12-10 16:45

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

提交回复
热议问题