Python if-else 一行式写法

Python if-else 一行式写法

1、常规写法

a, b, c = 1, 2, 0

if a > b:
    c = a
else:
    c = b
print(f'c = {c}')

输出 c=2
2、一行式写法

a, b, c = 1, 2, 0

c = a if a > b else b
print(f'c = {c}')

输出 c=2

3、范例

epsilon = 0.001
epsilon_decay = 0.9
epsilon = epsilon * epsilon_decay if epsilon > 0.01 else epsilon
print(epsilon)
epsilon = 0.2
epsilon_decay = 0.9
epsilon = epsilon * epsilon_decay if epsilon > 0.01 else epsilon
print(epsilon)

 

发表回复

您的电子邮箱地址不会被公开。