Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python มี Ternary Conditional Operator หรือไม่?

Ternary operator ถูกเพิ่มเข้ามาใน Python 2.5 ไวยากรณ์คือ:

Syntax

x if expr == True else y

ตัวอย่าง

ตัวอย่างต่อไปนี้แสดงการใช้งาน

>> percent = 59
>>> 'pass' if percent >= 50 else 'fail'
'pass'
>>> percent = 45
>>> 'pass' if percent >= 50 else 'fail'
'fail'