Python's interesting if-else usage

1. Ordinary writing

a, b = 1, 2
if a > b:
    c = a
else:
    c = b
print(c)

2. if ... else one-line expression

# 当if为真时,c = a, 否则 c = b
c = a if a > b else b

3. List

# 利用 a > b 表达式的比较值当做索引,True、False值等于1、0
a, b = 1, 2
c = [b, a][a > b]  # False  索引 = 0
print(c)  # 2

4. Logical operations

c = (a > b and a or b)
# a > b 为 True: True and a or b  == a
# a > b 为 False: False and a or b  == b

Here is a more interesting look at the Boolean value in Python, the value of False, the operation rules of and and or

# 为0,空集合,空字符串,空值None 布尔值为False
print(bool(0))
print(bool(""))  # False
print(bool([]))  # False
print(bool({
    
    }))  # False
print(bool(()))  # False
print(bool(0j))  # 虚数  False
print(bool(None))  # False
print(bool(0.0))  # False

When all values ​​in a Boolean context are true, and returns the last true value.
When a value in a Boolean context is false, and returns the first false value.
When all values ​​in a Boolean context are false, or returns the last false value.
or returns the first true value when one of the values ​​in a Boolean context is true.

d, e, f, g = 12, "", 34, 0
print(d and f)  # 34
print(d and g)  # 0
print(e and g)  # ""
print(e or g)  # 0
print(d or e)  # 12
print(d and e and f and g)  # ""
print(d or e or f or g)  # 12
print(d and e or g)  # 0

Guess you like

Origin blog.csdn.net/qq_43325582/article/details/122544661