Python 三元運算子

重拾很久沒碰的 Python,大部分已經忘光光,包含三元運算子是圓的還是扁的都不記得了...

Python 中的 if else:
    
    number = 100

    if number < 100:
        print("number is less than 100")
    elif number > 100:
        print("number is greater than 100")
    else:
        print("number is equal to 100")
    

三元運算子:
    
number = 100

result = "number is less than 100" if number < 100 else "number is greater than 100"
print(result)

    

與上面 if else 等效的三元運算子:
    
number = 100

result = "number is less than 100" if number < 100 else "number is greater than 100" if number > 100 else "number is equal to 100"
print(result)

    

如果覺得太長,可以這樣拆分:
    
number = 100

result = ("number is less than 100" if number < 100
          else "number is greater than 100" if number > 100
          else "number is equal to 100")
          
print(result)

    



參考資料:
PEP 308 – Conditional Expressions

留言