如果语句不符合条件

时间:2019-08-01 10:49:23

标签: python

如果我没有选择正确的数据,我有很多条件,因此我的语法可能有问题

我尝试将'is'更改为'=='但没有骰子

 for CCode in CleanNumbers:
        CountryInitial = phonenumbers.region_code_for_number(CCode)            
            if CountryInitial is 'HK' or 'SG' or 'ID' or 'JP' \
                or 'MO' or 'MY' or 'KR' or 'TW':
                print(CountryInitial)

期望:HK SG ID等(仅符合条件的那个)

结果:我在CleanNumbers数组中拥有的每个值

3 个答案:

答案 0 :(得分:4)

您的代码基本上检查'SG'是否为空。试试这个:

 for CCode in CleanNumbers:
        CountryInitial = phonenumbers.region_code_for_number(CCode)            
            if CountryInitial in ['HK', 'SG', 'ID', 'JP', 'MO', 'MY', 'KR', 'TW']:
                print(CountryInitial)

答案 1 :(得分:0)

如果您确实要使用or,则需要再次输入完整的条件:if CountryInitial is 'HK' or CountryInitial is 'SG' ...

使用or 'SG' or 'TH'等将验证字符串是否为空。

已经建议使用较短的版本,但为完整起见,请使用列表:if CountryInitial in ['HK', 'SG, ...]

答案 2 :(得分:0)

没关系,我认为它应该看起来像这样

for CCode in CleanNumbers:
        CountryInitial = phonenumbers.region_code_for_number(CCode)            
            if CountryInitial is 'HK' or CountryInitial is 'SG' or CountryInitial is               'ID' or CountryInitial is 'JP' \
                or 'MO' or 'MY' or 'KR' or 'TW':
                print(CountryInitial)
相关问题