三元运算符通常在Python里被称为条件表达式,这些表达式基于真(true)/假(false)的条件判断,在Python 2.4以上才有了三元操作。
下面是一个伪代码和例子:
伪代码:
#如果条件为真,返回真 否则返回假 condition_is_true if condition else condition_is_false
|
1
2
|
#如果条件为真,返回真 否则返回假
condition_is_true
if
condition
else
condition_is_false
|
例子:
is_fat = True state = "fat" if is_fat else "not fat"
|
1
2
|
is_fat
=
True
state
=
"fat"
if
is_fat
else
"not fat"
|
它允许用简单的一行快速判断,而不是使用复杂的多行if语句。 这在大多数时候非常有用,而且可以使代码简单可维护。
如果不用三元运算符则需要这么写
# -*- coding: utf-8 -*- __author__ = 'songhao' co = True if co: print("co is True") else: print("co is Flase") """pythonic 写法""" print("co is true") if not co else print("co is false")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# -*- coding: utf-8 -*-
__author__
=
'songhao'
co
=
True
if
co
:
print
(
"co is True"
)
else
:
print
(
"co is Flase"
)
"""pythonic 写法"""
print
(
"co is true"
)
if
not
co
else
print
(
"co is false"
)
|
结果是:
522

被折叠的 条评论
为什么被折叠?



