Pythonの基本データ型
これで、https://realpython.com/interacting-with-python/[Pythonインタープリターと対話してPythonコードを実行する方法]がわかりました。 Python言語を掘り下げてみましょう。 最初に、Pythonに組み込まれている基本的なデータ型について説明します。
このチュートリアルで学ぶことは次のとおりです
-
Pythonに組み込まれているいくつかの基本的な*数値、文字列*、および*ブール*型について学習します。 このチュートリアルの終わりまでに、これらのタイプのオブジェクトがどのように見えるか、そしてそれらをどのように表現するかを理解できます。
-
また、Pythonの組み込みの*関数*の概要も取得します。これらは、事前に作成されたコードの塊であり、便利なことを行うために呼び出すことができます。 すでに組み込みの `+ print()+`関数を見てきましたが、他にもたくさんあります。
無料のPDFダウンロード: Python 3 Cheat Sheet
-
__クイズを受ける:*インタラクティブな「Pythonの基本データ型」クイズで知識をテストします。 完了すると、学習の進捗状況を経時的に追跡できるようにスコアを受け取ります。
link:/quizzes/python-data-types/[クイズに挑戦»]
整数
Python 3では、整数値の長さに制限はありません。 もちろん、すべてのものと同様に、システムにあるメモリの量によって制約されますが、それを超えると、整数は必要な限り長くなります:
>>>
>>> print(123123123123123123123123123123123123123123123123 + 1)
123123123123123123123123123123123123123123123124
Pythonは、プレフィックスなしの一連の10進数を10進数として解釈します。
>>>
>>> print(10)
10
次の文字列を整数値の前に追加して、10以外の基数を示すことができます。
Prefix | Interpretation | Base |
---|---|---|
|
Binary |
2 |
|
Octal |
8 |
|
Hexadecimal |
16 |
例えば:
>>>
>>> print(0o10)
8
>>> print(0x10)
16
>>> print(0b10)
2
10進数以外の整数値の詳細については、次のWikipediaサイトを参照してください:https://en.wikipedia.org/wiki/Binary_number[Binary]、https://en.wikipedia.org/wiki/Octal[Octal ]、およびhttps://en.wikipedia.org/wiki/Hexadecimal[Hexadecimal]。
Python整数の基本型は、それを指定するために使用されるベースに関係なく、 `+ int +`と呼ばれます:
>>>
>>> type(10)
<class 'int'>
>>> type(0o10)
<class 'int'>
>>> type(0x10)
<class 'int'>
*注:*これは、REPLセッション中に値を表示する場合、 `+ print()`関数を使用する必要がないことを言及する良い機会です。 ` >>> +`プロンプトで値を入力し、[。keys]#Enter#を押すだけで表示されます:
>>>
>>> 10
10
>>> 0x10
16
>>> 0b10
2
このチュートリアルシリーズの例の多くは、この機能を使用します。
これはスクリプトファイル内では機能しないことに注意してください。 スクリプトファイルの行に単独で表示される値は何もしません。
浮動小数点数
Pythonの `+ float `タイプは、浮動小数点数を指定します。 ` float `値は小数点で指定されます。 オプションで、文字「 e 」または「 E +」とそれに続く正または負の整数を追加して、https://en.wikipedia.org/wiki/Scientific_notation [scientific notation]を指定できます。
>>>
>>> 4.2
4.2
>>> type(4.2)
<class 'float'>
>>> 4.
4.0
>>> .2
0.2
>>> .4e7
4000000.0
>>> type(.4e7)
<class 'float'>
>>> 4.2e-4
0.00042
_ _ ディープダイブ:浮動小数点表現
以下は、Pythonが内部的に浮動小数点数を表現する方法に関するもう少し詳細な情報です。 このレベルを理解していなくても、Pythonで浮動小数点数を簡単に使用できます。そのため、これが過度に複雑になっても心配しないでください。 興味がある場合に備えて、ここに情報を示します。
ほとんどすべてのプラットフォームは、https://en.wikipedia.org/wiki/IEEE_754_revision [IEEE 754]標準に従って、Pythonの `+ float `値を64ビットの「倍精度」値として表します。 その場合、浮動小数点数の最大値は約1.8 approximately 10 ^ 308 ^です。 Pythonは、文字列 ` inf +`によってそれより大きい数を示します。
>>>
>>> 1.79e308
1.79e+308
>>> 1.8e308
inf
ゼロになり得る非ゼロの数値に最も近いのは、約5.0⨉10 ^ -324 ^です。 それよりゼロに近いものは事実上ゼロです:
>>>
>>> 5e-324
5e-324
>>> 1e-325
0.0
浮動小数点数は、内部的に2進(基数2)分数として表されます。 ほとんどの小数部は2進小数部として正確に表現できないため、ほとんどの場合、浮動小数点数の内部表現は実際の値の近似値です。 実際には、実際の値と表示される値の差は非常に小さく、通常は重大な問題を引き起こすことはありません。 _ _
参考資料: Pythonでの浮動小数点表現と関連する潜在的な落とし穴の詳細については、https://docs.python.org/3.6/tutorial/floatingpoint.html [浮動小数点演算:問題と制限]を参照してください。 Pythonドキュメント。
複素数
複素数は、「+ <実部> + <虚部> j +」として指定されます。 例えば:
>>>
>>> 2+3j
(2+3j)
>>> type(2+3j)
<class 'complex'>
文字列
文字列は、文字データのシーケンスです。 Pythonの文字列型は `+ str +`と呼ばれます。
文字列リテラルは、一重引用符または二重引用符を使用して区切ることができます。 開始区切り文字と一致する終了区切り文字の間のすべての文字は、文字列の一部です。
>>>
>>> print("I am a string.")
I am a string.
>>> type("I am a string.")
<class 'str'>
>>> print('I am too.')
I am too.
>>> type('I am too.')
<class 'str'>
Pythonの文字列には、必要な数の文字を含めることができます。 唯一の制限は、マシンのメモリリソースです。 文字列は空にすることもできます:
>>>
>>> ''
文字列自体の一部として引用文字を含めたい場合はどうしますか? あなたの最初の衝動は、次のようなものを試すことです:
>>>
>>> print('This string contains a single quote (') character.')
SyntaxError: invalid syntax
ご覧のとおり、それはあまりうまくいきません。 この例の文字列は一重引用符で開きます。したがって、Pythonは次の単一引用符、つまり文字列の一部となるかっこ内の引用符が閉じ区切り文字であると想定します。 その場合、最後の単一引用符は迷い、表示される構文エラーを引き起こします。
文字列内にいずれかのタイプの引用文字を含める場合、最も簡単な方法は、文字列を他のタイプで区切ることです。 文字列に一重引用符を含める場合は、二重引用符で区切ります。逆も同様です。
>>>
>>> print("This string contains a single quote (') character.")
This string contains a single quote (') character.
>>> print('This string contains a double quote (") character.')
This string contains a double quote (") character.
文字列のエスケープシーケンス
場合によっては、Pythonで文字列内の文字または文字シーケンスを異なる方法で解釈する必要があります。 これは、次の2つの方法のいずれかで発生する可能性があります。
-
特定の文字は通常文字列内で与えられるという特別な解釈を抑制したい場合があります。
-
通常は文字どおりに解釈される文字列内の文字に特別な解釈を適用することができます。
バックスラッシュ( + \ +
)文字を使用してこれを達成できます。 文字列内のバックスラッシュ文字は、それに続く1つ以上の文字を特別に扱う必要があることを示します。 (これはエスケープシーケンスと呼ばれます。これは、バックスラッシュによって後続の文字シーケンスが通常の意味を「エスケープ」するためです。)
これがどのように機能するか見てみましょう。
特殊文字の意味の抑制
文字列に引用文字を含めようとすると、直面する可能性のある問題をすでに見ました。 文字列が一重引用符で区切られている場合、文字列の一部として一重引用符を直接指定することはできません。その文字列では、一重引用符が特別な意味を持ち、文字列を終了するからです。
>>>
>>> print('This string contains a single quote (') character.')
SyntaxError: invalid syntax
文字列の引用文字の前にバックスラッシュを指定すると、文字が「エスケープ」され、Pythonは通常の特別な意味を抑制します。 次に、単純なリテラル一重引用符文字として解釈されます。
>>>
>>> print('This string contains a single quote (\') character.')
This string contains a single quote (') character.
同じことは、二重引用符で区切られた文字列でも機能します。
>>>
>>> print("This string contains a double quote (\") character.")
This string contains a double quote (") character.
以下は、Pythonが文字列内の文字の通常の特別な解釈を抑制するエスケープシーケンスの表です。
Escape + Sequence | Usual Interpretation of + Character(s) After Backslash | “Escaped” Interpretation |
---|---|---|
|
Terminates string with single quote opening delimiter |
Literal single quote ( |
|
Terminates string with double quote opening delimiter |
Literal double quote ( |
|
Terminates input line |
Newline is ignored |
|
Introduces escape sequence |
Literal backslash ( |
通常、改行文字は行入力を終了します。 したがって、文字列の途中で[.keys]#Enter#を押すと、Pythonは不完全であると判断します。
>>>
>>> print('a
SyntaxError: EOL while scanning string literal
文字列を複数行に分割するには、各改行の前にバックスラッシュを含めます。改行は無視されます:
>>>
>>> print('a\
... b\
... c')
abc
文字列にリテラルバックスラッシュを含めるには、バックスラッシュでエスケープします。
>>>
>>> print('foo\\bar')
foo\bar
キャラクターに特別な意味を適用する
次に、タブ文字を含む文字列を作成する必要があるとします。 一部のテキストエディタでは、タブ文字をコードに直接挿入できます。 しかし、多くのプログラマーは、いくつかの理由で、その悪い練習を考慮します:
-
コンピューターはタブ文字と一連のスペース文字を区別できますが、できません。 コードを読む人間にとって、タブ文字とスペース文字は視覚的に区別できません。
-
一部のテキストエディターは、タブ文字を適切な数のスペースに展開することでタブ文字を自動的に削除するように構成されています。
-
一部のPython REPL環境では、コードにタブが挿入されません。
Python(および他のほとんどすべての一般的なコンピューター言語)では、タブ文字はエスケープシーケンス `+ \ t +`で指定できます。
>>>
>>> print('foo\tbar')
foo bar
エスケープシーケンス `+ \ t `により、 ` t `文字は通常の意味、つまりリテラル ` t +`の意味を失います。 代わりに、組み合わせはタブ文字として解釈されます。
Pythonに文字どおりに解釈する代わりに特別な意味を適用させるエスケープシーケンスのリストを次に示します。
Escape Sequence | “Escaped” Interpretation |
---|---|
|
ASCII Bell ( |
|
ASCII Backspace ( |
|
ASCII Formfeed ( |
|
ASCII Linefeed ( |
|
Character from Unicode database with given |
|
ASCII Carriage Return ( |
|
ASCII Horizontal Tab ( |
|
Unicode character with 16-bit hex value |
|
Unicode character with 32-bit hex value |
|
ASCII Vertical Tab ( |
|
Character with octal value |
|
Character with hex value |
例:
>>>
>>> print("a\tb")
a b
>>> print("a\141\x61")
aaa
>>> print("a\nb")
a
b
>>> print('\u2192 \N{rightwards arrow}')
→ →
このタイプのエスケープシーケンスは、通常、キーボードから簡単に生成されない文字や、簡単に読み取りまたは印刷できない文字を挿入するために使用されます。
生ストリング
生の文字列リテラルの前には、「+ r 」または「 R +」が付きます。これらは、関連する文字列のエスケープシーケンスが変換されないことを指定します。 バックスラッシュ文字は文字列に残ります:
>>>
>>> print('foo\nbar')
foo
bar
>>> print(r'foo\nbar')
foo\nbar
>>> print('foo\\bar')
foo\bar
>>> print(R'foo\\bar')
foo\\bar
トリプルクォート文字列
Pythonには文字列を区切るさらに別の方法があります。 三重引用符で囲まれた文字列は、3つの単一引用符または3つの二重引用符の一致グループによって区切られます。 エスケープシーケンスは、トリプルクォートで囲まれた文字列でも機能しますが、シングルクォート、ダブルクォート、改行をエスケープせずに含めることができます。 これにより、単一引用符と二重引用符の両方を含む文字列を作成する便利な方法が提供されます。
>>>
>>> print('''This string has a single (') and a double (") quote.''')
This string has a single (') and a double (") quote.
改行をエスケープせずに含めることができるため、これにより複数行の文字列も許可されます。
>>>
>>> print("""This is a
string that spans
across several lines""")
This is a
string that spans
across several lines
Pythonプログラム構造に関する今後のチュートリアルで、三重引用符で囲まれた文字列を使用して、説明的なコメントをPythonコードに追加する方法を説明します。
ブール型、ブールコンテキスト、および「真実性」
Python 3はブールデータ型を提供します。 ブール型のオブジェクトには、2つの値、「+ True 」または「 False +」のいずれかがあります。
>>>
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
今後のチュートリアルで説明するように、Pythonの式は、ブールコンテキストで評価されることがよくあります。つまり、真偽を表すと解釈されます。 ブールコンテキストでtrueである値は「真である」と呼ばれることがあり、ブールコンテキストでfalseである値は「偽である」と呼ばれます。 (「偽」と綴られた「偽」も表示される場合があります。)
ブール型のオブジェクトの「真実性」は自明です。「+ True 」に等しいブールオブジェクトは真実(true)であり、「 False +」に等しいオブジェクトは偽(false)です。 ただし、非ブールオブジェクトはブールコンテキストでも評価され、trueまたはfalseであると判断されます。
Pythonの演算子と式に関する今後のチュートリアルで論理演算子に出会うと、ブールコンテキストでのオブジェクトの評価の詳細がわかります。
組み込み関数
Pythonインタープリターは、組み込みの多くの関数をサポートします:68、Python 3.6の時点で。 これらの多くは、前後の文脈で取り上げられるため、以下の説明で取り上げます。
とりあえず、利用可能なものの感触を示すために、簡単な概要を説明します。 詳細については、https://docs.python.org/3.6/library/functions.html [組み込み関数に関するPythonドキュメント]を参照してください。 以下の説明の多くは、今後のチュートリアルで説明するトピックと概念を参照しています。
Math
Function | Description |
---|---|
|
Returns absolute value of a number |
|
Returns quotient and remainder of integer division |
|
Returns the largest of the given arguments or items in an iterable |
|
Returns the smallest of the given arguments or items in an iterable |
|
Raises a number to a power |
|
Rounds a floating-point value |
|
Sums the items of an iterable |
型変換
Function | Description |
---|---|
|
Returns a string containing a printable representation of an object |
|
Converts an integer to a binary string |
|
Converts an argument to a Boolean value |
|
Returns string representation of character given by integer argument |
|
Returns a complex number constructed from arguments |
|
Returns a floating-point object constructed from a number or string |
|
Converts an integer to a hexadecimal string |
|
Returns an integer object constructed from a number or string |
|
Converts an integer to an octal string |
|
Returns integer representation of a character |
|
Returns a string containing a printable representation of an object |
|
Returns a string version of an object |
|
Returns the type of an object or creates a new type object |
イテラブルとイテレータ
Function | Description |
---|---|
|
Returns |
|
Returns |
|
Returns a list of tuples containing indices and values from an iterable |
|
Filters elements from an iterable |
|
Returns an iterator object |
|
Returns the length of an object |
|
Applies a function to every item of an iterable |
|
Retrieves the next item from an iterator |
|
Generates a range of integer values |
|
Returns a reverse iterator |
|
Returns a |
|
Returns a sorted list from an iterable |
|
Creates an iterator that aggregates elements from iterables |
複合データ型
Function | Description |
---|---|
|
Creates and returns an object of the |
|
Creates and returns a |
|
Creates a |
|
Creates a |
|
Constructs a |
|
Returns a new featureless object |
|
Creates a |
|
Creates a |
クラス、属性、および継承
Function | Description |
---|---|
|
Returns a class method for a function |
|
Deletes an attribute from an object |
|
Returns the value of a named attribute of an object |
|
Returns |
|
Determines whether an object is an instance of a given class |
|
Determines whether a class is a subclass of a given class |
|
Returns a property value of a class |
|
Sets the value of a named attribute of an object |
|
Returns a proxy object that delegates method calls to a parent or sibling class |
入出力
Function | Description |
---|---|
|
Converts a value to a formatted representation |
|
Reads input from the console |
|
Opens a file and returns a file object |
|
Prints to a text stream or the console |
変数、参照、およびスコープ
Function | Description |
---|---|
|
Returns a list of names in current local scope or a list of object attributes |
|
Returns a dictionary representing the current global symbol table |
|
Returns the identity of an object |
|
Updates and returns a dictionary representing current local symbol table |
|
Returns |
その他
Function | Description |
---|---|
|
Returns |
|
Compiles source into a code or AST object |
|
Evaluates a Python expression |
|
Implements dynamic execution of Python code |
|
Returns the hash value of an object |
|
Invokes the built-in help system |
|
Returns a memory view object |
|
Returns a static method for a function |
|
Invoked by the |
結論
このチュートリアルでは、Pythonが提供する組み込みの*データ型*および*関数*について学びました。
これまでに示した例では、定数値のみを操作および表示しています。 ほとんどのプログラムでは、通常、プログラムの実行に応じて価値が変化するオブジェクトを作成する必要があります。
次のチュートリアルに進んで、Python *変数*について学習してください。
-
__クイズを受ける:*インタラクティブな「Pythonの基本データ型」クイズで知識をテストします。 完了すると、学習の進捗状況を経時的に追跡できるようにスコアを受け取ります。
link:/quizzes/python-data-types/[クイズに挑戦»]