1. 程式人生 > >9.if/else/elif

9.if/else/elif

 

簡單的條件是通過使用 if/else/elif 語法建立的。條件的括號是允許的,但不是必需的。考慮到基於表的縮排的性質,可以使用 elif 而不是 else/if 來維持縮排的級別。

if [expression]:
    statement(s) elif [expression]: statement(s) else: statement(s) 

簡短陳述可以寫在與條件相同的行上:

if 1 + 1 == 2: return 2 + 2 else: var x = 3 + 3 return x 

Sometimes you might want to assign a different initial value based on a boolean expression. In this case, ternary-if expressions come in handy:

var x = [value] if [expression] else [value] y += 3 if y < 10 else -1