天假之名 发表于 2020-4-3 10:21:37

关于三元操作符

小甲鱼课上讲的三元操作符我好像不怎么理解,
麻烦各位再帮我解释一下

qiuyouzhi 发表于 2020-4-3 10:29:23

想象一下倒装句?

qiuyouzhi 发表于 2020-4-3 10:31:31

来看一段代码:
>>> hungry = True
>>> if hungry:
        eat = 'apple'
else:
        eat = None

       
>>> eat
'apple'
用人话来讲:
如果我饿了,我就吃苹果,否则就不吃
三元表达式:
>>> eat = 'apple' if hungry else None
>>> eat
'apple'
人话:
我要吃苹果,如果我饿了,否则就不吃

jackz007 发表于 2020-4-3 10:32:44

max = (a > b) ? a : b ; // 如果条件(a > b)成立,那么,max 等于问号后面的变量(a),否则,等于冒号后面的变量(b)。

天假之名 发表于 2020-4-3 10:39:23

qiuyouzhi 发表于 2020-4-3 10:31
来看一段代码:

用人话来讲:


你这个很形象啊

ouyunfu 发表于 2020-4-3 11:54:18

python中三元运算有两种实现方法:

一是通过if语句实现的,语法如下:

<true statement> if <condition expression> else <false statement>
三元运算首先对条件表达式<condition expression>求值,如果值为True,则执行<true statement>,否则执行<false statement>。如:

x=1
y=3
z= x-y if x>y else x+y
print(z)
在使用时要注意的Python2和Python3有一点小区别。在Python3中<true statement>和<false statement>可以是字面量也可以是函数调用,特别的还可以使用print语句。而在Python2中,只有<true statement>中可以使用print语句,<false statement>中不能使用,但是自定义的函数调用则不受限制。如:

#Python2中可以执行
print(x-y) if x>y else x+y
x-y if x>y else x+y
#Python2中不可以执行
x-y if x>y else print(x+y)
二是通过and、or来实现,此方式利用的是逻辑运算符的短路原则来实现的。语法如下:

<condition expression> and <true statement> or <false statement>
x=1
y=3
z= x>y and x-y or x+y
print(z)
 此实现方式在Python2和Python3同样有区别,在Python3中<true statement>和<false statement>可以是字面量也可以是函数调用,特别的还可以使用print语句。而在Python2中<true statement>和<false statement>不能使用print语句,但是调用函数是可以的。

#Python2中可以执行
x>y and "x" or "y"
x-y if x>y else x+y
#Python2中不可以执行
x>y and print("x") or "y"
x>y and "x" or print("y")

永恒的蓝色梦想 发表于 2020-4-3 12:18:18

ouyunfu 发表于 2020-4-3 11:54
python中三元运算有两种实现方法:

一是通过if语句实现的,语法如下:


这个 and 和 or 的二元操作符学到了
页: [1]
查看完整版本: 关于三元操作符