讀古今文學網 > 父與子的編程之旅:與小卡特一起學Python > 7.7 使用 and >

7.7 使用 and

上面最後這個例子可以達到目的。不過還有一種更簡便的方法來做同樣的事情。可以像下面這樣結合兩個條件:

我們使用 and 關鍵字來結合這兩個條件。and 表示兩個條件都必須為真才能執行下面的代碼塊。

可以用 and 把兩個以上的條件放在一起:

age = float(raw_input("Enter your age: "))grade = int(raw_input("Enter your grade: "))color = raw_input("Enter your favorite color: ")if age >= 8 and grade >= 3 and color == "green":    print "You are allowed to play this game."else:    print "Sorry, you can't play the game."  

如果有兩個以上的條件,所有條件都必須為真,這個 if 語句才能為真。

還有其他方法來結合多個條件。