Files
freeCodeCamp/guide/chinese/python/ternary-operator/index.md
2018-10-16 21:32:40 +05:30

39 lines
931 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: Python Ternary Operater
localeTitle: Python三元歌剧
---
# Python中的三元运算符
Python中的三元操作通常也称为条件表达式允许程序员执行评估并根据给定条件的真实性返回值。
三元运算符与标准`if` `else` `elif`结构的区别在于它不是控制流结构并且在Python语言中表现得更像其他运算符例如`==``!=`
### 例
在此示例中,如果`val`变量为偶数,则返回字符串`Even` ,否则返回字符串`Odd` 。然后将返回的字符串分配给`is_even`变量并打印到控制台。
#### 输入
```python
for val in range(1, 11):
is_even = "Even" if val % 2 == 0 else "Odd"
print(val, is_even, sep=' = ')
```
#### 产量
```
1 = Odd
2 = Even
3 = Odd
4 = Even
5 = Odd
6 = Even
7 = Odd
8 = Even
9 = Odd
10 = Even
```
### 来源
https://docs.python.org/2.5/whatsnew/pep-308.html