「変数とオブジェクト」の編集履歴(バックアップ)一覧に戻る
変数とオブジェクト - (2025/03/22 (土) 23:21:38) のソース
** 目次 #contents ** 変数の型を調べる type関数を使う。引数に変数を指定する。 #highlight(){{ >>> 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関数にはリテラルも指定することができる。 #highlight(){{ >>> type(1) <class 'int'> >>> type(2.3) <class 'float'> >>> type('スノウブレイクのリフ') <class 'str'> >>> type(True) <class 'bool'> }} ** 変数の値を入れ替える コンマを使用して代入演算子で代入する。 #highlight(){{ >>> x = 2 >>> y = 4 >>> print(x, y) 2 4 >>> x, y = y, x >>> print(x, y) 4 2 }} ** オブジェクトのブール値(真偽)を調べる bool関数を使う。引数に与えたオブジェクトがTrue(真)かFalse(偽)のどちらか判定して返す。 #highlight(){{ >>> 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))