Python(変数とオブジェクト)

2025年3月22日 (土)

[Python]オブジェクトのブール値(真偽)を調べる

bool関数を使う。引数に与えたオブジェクトがTrue(真)かFalse(偽)のどちらか判定して返す。

>>> bool(0)
False
>>> bool(1)
True
>>> bool(0)
False
>>> bool(1)
True
>>> bool(0.0)
False
>>> bool(1.2)
True
>>> bool('')
False
>>> bool('鈴木みのりさん、かわいい')
True
>>> bool([])
False
>>> bool(['セナディア', 'フレイア'])
True

公式のウェブサイトの説明によると、以下のオブジェクトが偽になるとのこと。

  • NoneとFalse(constants defined to be false: None and False)
  • 数値型の0(zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1))
  • 空のシーケンスとコレクション(empty sequences and collections: '', (), [], {}, set(), range(0))

2025年3月18日 (火)

[Python]変数の型を調べる

type関数を使う。引数に変数を指定する。

>>> n = 1; d = 2.3; s = 'スノウブレイクのリフ'; b = True;
>>> type(n)
<class 'int'>
>>> type(d)
<class 'float'>
>>> type(s)
<class 'str'>
>>> type(b)
<class 'bool'>
>>> type(len)
<class 'builtin_function_or_method'>

type関数にはリテラルも指定することができる。

>>> type(1)
<class 'int'>
>>> type(2.3)
<class 'float'>
>>> type('スノウブレイクのリフ')
<class 'str'>
>>> type(True)
<class 'bool'>

 

無料ブログはココログ

■■

■■■