While 循环单行 [英] While loop one-liner

查看:36
本文介绍了While 循环单行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在一行中单独使用 python while 循环,我已经尝试过:

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

但它会产生一个错误信息:if 语句处的Invalid Syntax

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

推荐答案

当使用 复合python 中的语句(需要套件、缩进块的语句),并且该块仅包含简单语句,可以去掉换行符,简单语句用分号隔开.

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.

所以:

if expression: print "something"

有效,但是

while expression: if expression: print "something"

不是,因为 whileif 语句都是复合语句.

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

对于您的特定示例,您可以将 if 表达式:赋值 部分替换为 条件表达式,因此通过使用表达式而不是复杂的语句:

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

一般来说,或 while n<1000: rn += n if not (n % 3 and n % 5) else 0 特别是.

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.

这篇关于While 循环单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆