iT邦幫忙

2018 iT 邦幫忙鐵人賽
0
自我挑戰組

if len(learning.python) == 30:系列 第 29

Day29-if-成立或不成立

  • 分享至 

  • xImage
  •  

概觀

任何object都可以被驗證真假值。預設為True,除非該class有以下其中一情況

  • 定義__bool__()且回傳False
  • 定義__len__()且回傳0

不成立名單

built-in objects

category what
constants None
False
numeric type 0
0.0
0j
Decimal(0)
Fraction(0, 1)
empty sequences and collections ''
()
[]
{}
set()
range(0)
from decimal import Decimal
from fractions import Fraction


def test_if_behavior(test_obj):
    is_true = '{} is ture'
    is_false = '{} is false'
    if test_obj:
        print(is_true.format(test_obj))
    else:
        print(is_false.format(test_obj))


def show_type(test_obj):
    print('type of {} is {}'.format(test_obj, type(test_obj)))


constants = None, False
for c in constants:
    show_type(c)
    test_if_behavior(c)

# type of None is <class 'NoneType'>
# None is false
# type of False is <class 'bool'>
# False is false


numeric_type = 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
for n in numeric_type:
    show_type(n)
    test_if_behavior(n)

# type of 0 is <class 'int'>
# 0 is false
# type of 0.0 is <class 'float'>
# 0.0 is false
# type of 0j is <class 'complex'>
# 0j is false
# type of 0 is <class 'decimal.Decimal'>
# 0 is false
# type of 0 is <class 'fractions.Fraction'>
# 0 is false


empty_sequences_and_collections = '', (), [], {}, set(), range(0)
for esc in empty_sequences_and_collections:
    print('len of {} is {}'.format(esc, len(esc)))
    show_type(esc)
    test_if_behavior(esc)

# len of  is 0
# type of  is <class 'str'>
#  is false
# len of () is 0
# type of () is <class 'tuple'>
# () is false
# len of [] is 0
# type of [] is <class 'list'>
# [] is false
# len of {} is 0
# type of {} is <class 'dict'>
# {} is false
# len of set() is 0
# type of set() is <class 'set'>
# set() is false
# len of range(0, 0) is 0
# type of range(0, 0) is <class 'range'>
# range(0, 0) is false

參考


上一篇
Day28-enum
下一篇
Day30-print-statement或function
系列文
if len(learning.python) == 30:31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言