三元运算(三目运算),是对简单的条件语句的缩写。

#书写格式:

result = 值1 if 条件 else 值2

#如果条件成立,那将值1赋值给result变量,否则,将值2赋值给result变量

示例:

 

name = "alex" if 1 == 1 else "eric"
print(name)
#打印结果:alex


name = "alex" if 1 == 0 else "eric"
print(name)
#打印结果:eric

 

相关文章:

  • 2021-09-28
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2021-11-19
  • 2021-12-17
相关资源
相似解决方案