if expression: statement(s) else: statement(s)
#!/usr/bin/python3 amount=int(input("Enter amount: ")) if amount<1000: discount=amount*0.05 print ("Discount",discount) else: discount=amount*0.10 print ("Discount",discount) print ("Net payable:",amount-discount)
在上面的例子中,discount 計算是一個輸入的數量。如果用量少於1000折扣率是5%,而高於10000折扣率是10%。 當執行上面的程式碼,它產生以下結果 -
Enter amount: 600 Discount 30.0 Net payable: 570.0 Enter amount: 1200 Discount 120.0 Net payable: 1080.0
類似於else,elif語句是可選的。然而,不同於else,它至多有一個語句, if 下面可以有任意數的 elif 語句。
if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s)
Python核心程式設計不提供在其他語言中的switch或case語句,但我們可以用if..elif...語句來模擬 switch case 如下-
#!/usr/bin/python3 amount=int(input("Enter amount: ")) if amount<1000: discount=amount*0.05 print ("Discount",discount) elif amount<5000: discount=amount*0.10 print ("Discount",discount) else: discount=amount*0.15 print ("Discount",discount) print ("Net payable:",amount-discount)
Enter amount: 600 Discount 30.0 Net payable: 570.0 Enter amount: 3000 Discount 300.0 Net payable: 2700.0 Enter amount: 6000 Discount 900.0 Net payable: 5100.0