2016-02-07 57 views
0
if instanceType == instance_type and operatingSystem == operating_system and tenancy == tenancy_db: 
    sku_list.append(key) 

在這個if語句中,這些變量,instanceType,operatingSystem和tenancy是用戶輸入,如何處理不檢查用戶輸入是否爲None。如何處理if語句和python中的運算符?

例如如果instanceType是無,我想檢查

if operatingSystem == operating_system and tenancy == tenancy_db: 
    sku_list.append(key) 

例如,如果operatingSystem是None,我想檢查

if instanceType == instance_type and tenancy == tenancy_db: 
    sku_list.append(key) 

例如,如果兩個租戶和instanceType是無,我想檢查:

if operatingSystem == operating_system: 
    sku_list.append(key) 

Simliarly,這取決於在無或別的東西不管用戶輸入,有沒有其他辦法可以做到這一點,或者我要實現嵌套如果別的?

回答

2

一種方法是申報一個輔助功能:

equal_or_none = lambda x, y: x is None or x == y 
if (
     equal_or_none(instanceType, instance_type) 
     and equal_or_none(operatingSystem, operating_system) 
     and equal_or_none(tenancy, tenancy_db)): 
    sku_list.append(key) 
1

您還可以使用or運營商將治療None假:

if (instanceType or instance_type) == instance_type and \ 
    (operatingSystem or operating_system) == operating_system and \ 
    (tenancy or tenancy_db) == tenancy_db: 
    sku_list.append(key)