Intro to Python
変数とオブジェクト
最終更新:
introtopython
-
view
目次
変数の型を調べる
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'>
変数の値を入れ替える
コンマを使用して代入演算子で代入する。
>>> x = 2
>>> y = 4
>>> print(x, y)
2 4
>>> x, y = y, x
>>> print(x, y)
4 2
オブジェクトのブール値(真偽)を調べる
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))