在一行上添加一个简单的if-then-else语句 [英] Putting a simple if-then-else statement on one line

查看:160
本文介绍了在一行上添加一个简单的if-then-else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Python三元运算符

我刚刚进入Python而且我非常喜欢语法的简洁性。但是,有一种更简单的方法来编写如果 - 然后 - else 声明所以它适合一行?

I'm just getting into Python and I really like the terseness of the syntax. However, is there an easier way of writing an if-then-else statement so it fits on one line?

例如:

if count == N:
    count = 0
else:
    count = N + 1

有没有更简单的方法来写这个?我的意思是,在Objective-C中我会把它写成:

Is there a simpler way of writing this? I mean, in Objective-C I would write this as:

count = count == N ? 0 : count + 1;

Python有类似内容吗?

Is there something similar for Python?

更新

我知道在这个例子中我可以使用 count ==(count + 1)%N

I know that in this instance I can use count == (count + 1) % N.

我在询问一般语法。

推荐答案

那是更具体地说,一个三元运算符表达式而不是if-then,这里是python语法

That's more specifically a ternary operator expression than an if-then, here's the python syntax

value_when_true if condition else value_when_false

更好的例子:(感谢伯恩斯先生

'是'如果水果=='Apple'否则'否'

现在分配和if语法对比

fruit = 'Apple'
isApple = True if fruit == 'Apple' else False

vs

fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True

这篇关于在一行上添加一个简单的if-then-else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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