1. 程式人生 > 實用技巧 >【Python基礎知識】(四)比較運算子、邏輯運算子和if語句

【Python基礎知識】(四)比較運算子、邏輯運算子和if語句

比較運算子

1、檢查是否相等

  相等運算子(==):用來判斷二者是否“相等”,注意與賦值運算子(=)區分

car = 'audi'
'''在Python中判斷是否相等時區分大小寫'''
car == 'Audi'    '''False'''
car.title() == 'Audi'    '''True'''

2、檢查是否不相等

  (1)比較數字:小於(<)、小於等於(<=)、大於(>)、大於等於(>=)

age = 19

age < 21    '''True'''
age <= 21    '''True'''
age > 19 '''False''' age >= 19 '''True'''

  (2)條件判斷:不等於(!=)

requested_topping = 'mushrooms'

if requested_topping != 'anchovies':
    print( "Hold the anchovies!" )

邏輯運算子

  使用邏輯運算子andor可一次檢查多個條件,形成更復雜的判斷式。

age_0 = 22
age_1 = 18
age_0 >= 21 and age_1 >= 21    '''False'''
age_0 
>= 21 or age_1 >= 21 '''True''' age_1 = 22 age_0 >= 21 and age_1 >= 21 '''True'''

if語句

  上述程式中的判斷語句,均可作為if語句的條件測試。若測試值為真,Python將會執行if語句所包含的程式碼,若為假則不會執行。

1、簡單的if語句

age = 19
if age >= 18:
    print( "You are old enough to vote!" )

2、if-else語句

age = 17
if age >= 18:
    print
( "You are old enough to vote!" ) print( "Have you registered to vote yet?" ) else: print( "Sorry, you are too young to vote." ) print( "Please register to vote as soon as you turn 18!" )

輸出為:

Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!

  和for語句相同,當測試值為真時,Python會執行所有緊跟在if語句之後且縮排的程式碼

3、if-elif-else結構(elif意為else if)

age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 5

print( "Your admission cost is " + str(price) + " dollars." )

使用if語句處理列表

1、判斷列表是否為空

  當把列表名用作if語句的條件表示式時,Python將在列表至少包含一個元素時返回True,在列表為空時返回False。

requested_toppings = []
if requested_toppings:
    print( "not empty" )
else:
    print( "empty" )
'''列表為空,故列印empty'''

2、判斷元素是否在列表中

  使用in表示包含於列表,not in表示不包含於列表。

available_toppings = [ 'mushrooms', 'olives', 'green peppers', 
                                'pepperoni', 'pineapple', 'extra cheese' ]
requested_toppings = [ 'mushrooms', 'french fries', 'extra cheese' ]

for requested_topping in requested_toppings:
    if requested_topping not in available_toppings:
        print( "Sorry, we don't have " + requested_topping + "." )
    else:
        print( "Adding " + requested_topping + "." )

print( "\nFinished making your pizza!" )

輸出為:

Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.

Finished making your pizza!

參考書籍:《Python程式設計:從入門到實踐》

2020-07-09