「変数とオブジェクト」の編集履歴(バックアップ)一覧はこちら
変数とオブジェクト - (2025/03/22 (土) 23:21:38) の1つ前との変更点
追加された行は緑色になります。
削除された行は赤色になります。
** 目次
#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
}}
** 1行に複数の文(statement)を書く
スクリプトでも対話型実行環境でも、;記号(セミコロン)を使うことで1行に複数の文(statement)を書くことができる(Several simple statements may occur on a single line separated by semicolons.)。以下は、対話型実行環境で行った例。
#highlight(){{
>>> s1 = 'ウマ娘のメイショウドトウ役の'; s2 = '和多田美咲さん'; s3 = 'かわいい'
>>> print(s1 + s2 + s3)
ウマ娘のメイショウドトウ役の和多田美咲さんかわいい
}}
** 目次
#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))
表示オプション
横に並べて表示:
変化行の前後のみ表示: