python中的三元运算符 [英] Ternary operator in python

查看:153
本文介绍了python中的三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先生,我在python中使用三元运算符时遇到问题.

我在C/C ++中使用了三元运算符,例如C

Sir, I have a problem with ternary operator in python.

I have used the ternary operator in C/C++ e.g for C

int a = (5>9)? 2 : 3

就像这样

在这里,a的值被指定为3.

我像这样在python中尝试了相同的方法

it comes like this

Here the value of a is assigned to be 3.

I tried the same in python like this

>>>> a=5>9if 3 else 7
>>> print(a)


这里的输出为"False",所以我发现我的代码有零个错误,但输出为布尔值.

然后我像这样打字我的代码,


here the output comes "False" so I found that my code has zero errors but the output is in Boolean.

Then I typecast-ed my code like this,

>>>> a=int(5>9)if 3 else 7
>>> print(a)



输出为"0",这让我感到奇怪.

所以,我尝试过这样,



Here the output comes "0" which made me to wonder.

So, I tried like this,

>>> a=int(5>9)if int(3) else int(7)
>>> print(a)



但是输出仍然为零. python中有什么方法可以使用三元运算符.

我错过了什么吗?

请帮助我.谢谢.



But still the output is zero. Is there any way in python to use a ternary operator.

Have I missed anything?

Kindly help me with this.Thank you.

推荐答案

在Python中是:
如果5> a = 2,则a = 2. 9其他3

希望对您有所帮助.
In Python it is:
a = 2 if 5 > 9 else 3

I hope it helps.


这篇关于python中的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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