Pythonは動的かつ強い型付けのプログラミング言語です。 ダックタイピングと漸進的型付けの両方を、型ヒントを通じて取り入れています。 命令型、宣言型(たとえば関数型)、オブジェクト指向といったプログラミングの_スタイル_をすべてサポートしていますが、内部的には**Pythonではすべてがオブジェクト**です。
Pythonはコードの読みやすさを特に重視しており、(Haskellと同様に)関数・メソッド・クラスの定義を示すために有意なインデントを使います。
PythonはGuido van Rossumによって作られ、1991年に最初にリリースされました。 Python Software Foundationは、PythonとCPythonの開発に向けたリソースを管理・指揮しており、コミュニティのメンバーからPython Enhancement Proposals(PEP)を通じて言語の変更提案を受け取っています。
現在のリリースの完全なドキュメントはdocs.python.orgにあります。
この最初のコンセプトでは、Python言語の4つの主要な機能を紹介します。
defキーワードとreturnキーワード)、一般に、Pythonトラックのコンテンツ、テスト、アナライザーツールは、PythonのコードスタイルについてPEP 8とPEP 257で示されているスタイル規約に従います。さらに、1文字の変数名を使わないことが(強く)推奨されます。
Pythonの禅(PEP 20)とPythonicとは何か?には、さらなる哲学が示されています。
Pythonトラックでは、変数は常にsnake_caseで書き、定数はSCREAMING_SNAKE_CASEで書きます。
Pythonでは、変数や定数を作るためにキーワードを使う必要はありません。
代わりに、プログラマーは代入演算子=を使って、名前(_変数_とも呼ばれます)をどんな型のオブジェクトにも束縛できます。書き方は<name> = <value>です。
名前は、その生涯を通じて、別の値(別のオブジェクト型)に再代入(再束縛)できます。
たとえばmy_first_variableは、=を使って何度も再代入でき、再代入のたびに別のオブジェクト型を参照できます。
>>> my_first_variable = 1 # my_first_variable bound to an integer object of value one.
>>> my_first_variable = 2 # my_first_variable re-assigned to integer value 2.
>>> print(type(my_first_variable))
<class 'int'>
>>> print(my_first_variable)
2
>>> my_first_variable = "Now, I'm a string." # <--You may re-bind a name to a different object type and value.
>>> print(type(my_first_variable))
<class 'str'>
>>> my_first_variable = 'You can call me "str".' # <--Strings can be declared using single or double quote marks.
>>> print(my_first_variable)
You can call me "str".
>>> import collections
>>> my_first_variable = collections.Counter([1,1,2,3,3,3,4,5,6,7]) # <--Now my_first_variable has been re-bound to a Counter object.
>>> print(type(my_first_variable))
<class 'collections.Counter'>
>>> print(my_first_variable)
Counter({3: 3, 1: 2, 2: 1, 4: 1, 5: 1, 6: 1, 7: 1})
定数とは、プログラム内で一度だけ代入されることを意図した名前です。
これらはモジュール(ファイル)レベルで定義するもので、通常はプログラム内のすべての関数とクラスから参照できます。
SCREAMING_SNAKE_CASEを使うことで、その名前を再代入したり、値を変更したりすべきでないことを示します。
# All caps signal that this is intended as a constant.
MY_FIRST_CONSTANT = 16
# Re-assignment will be allowed by the compiler & interpreter,
# but this is VERY strongly discouraged.
# Please don't do this, it could create problems in your program!
MY_FIRST_CONSTANT = "Some other value"
Pythonでは、機能の単位は関数にカプセル化されており、関数自体もオブジェクトです(_どこまでも亀が続く_というわけです)。
関数は、単独で実行したり、他の関数の引数として渡したり、入れ子にしたり、クラスに束縛したりできます。 関数がクラス名に束縛されると、それらはメソッドと呼ばれます。 関連する関数やクラス(およびそのメソッド)は、同じファイルやモジュールにまとめることができ、他のプログラムで使うために一部または全部をインポートできます。
defキーワードで関数定義を始めます。
各関数は、()の括弧の中に0個以上の仮引数を書くことができ、その後に:のコロンが続きます。
関数の_本体_の文はdefの次の行から始まり、_ブロックとしてインデント_する必要があります。
# The body of a function is indented by 2 spaces & prints the sum of the numbers.
def add_two_numbers(number_one, number_two):
total = number_one + number_two
print(total)
>>> add_two_numbers(3, 4)
7
# Inconsistent indentation in your code blocks will raise an error.
>>> def add_three_numbers_misformatted(number_one, number_two, number_three):
... result = number_one + number_two + number_three # This was indented by 4 spaces.
... print(result) # <--This was only indented by 3 spaces.
...
...
File "<stdin>", line 3
print(result)
^
IndentationError: unindent does not match any outer indentation level
関数はreturnキーワードを使って、値やオブジェクトを_明示的に_返します。
# Function definition on first line, explicit return used on final line.
def add_two_numbers(number_one, number_two):
return number_one + number_two
# Calling the function in the Python shell returns the sum of the numbers.
>>> add_two_numbers(3, 4)
7
# Assigning the function call to a variable and printing
# the variable will also return the value.
>>> sum_with_return = add_two_numbers(5, 6)
>>> print(sum_with_return)
11
returnの後に_明示的な_式がない関数は、Noneオブジェクトを_暗黙的に_返します。
Noneの詳細は、後のコンセプトで扱います。
この演習と説明の目的では、Noneは何もないこと、つまりnullを表すプレースホルダーです。
# This function will return `None`
def square_a_number(number):
square = number * number
return # <-- note that this return is not followed by an expression
# Calling the function in the Python shell appears
# to not return anything at all.
>>> square_a_number(2)
>>>
# Using print() with the function call shows that
# the function is actually returning the **None** object.
>>> print(square_a_number(2))
None
returnを省略した関数も、Noneオブジェクトを_暗黙的に_返します。
つまり、関数内でreturnを使わなければ、Pythonが代わりにNoneオブジェクトを返します。
# This function omits a return keyword altogether
def add_two_numbers(number_one, number_two):
result = number_one + number_two
>>> add_two_numbers(5, 7)
>>> print(add_two_numbers(5, 7))
None
# Assigning the function call to a variable and printing
# the variable will also show None.
>>> sum_without_return = add_two_numbers(5, 6)
>>> print(sum_without_return)
None
関数を呼び出すには、名前の後に()を付けます。
クラスやモジュールの中で定義された関数を呼び出すには、ドット(.)記法を使います。
>>> def raise_to_power(number, power):
... return number ** power
...
>>> raise_to_power(3,3) # Invoking the function with the arguments 3 and 3.
27
# A mis-match between the number of parameters and the number of arguments will raise an error.
>>> raise_to_power(4,)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: raise_to_power() missing 1 required positional argument: 'power'
# Calling methods or functions in classes and modules.
>>> start_text = "my silly sentence for examples."
>>> str.upper(start_text) # <--Calling the upper() method from the built-in str class on start_text.
'MY SILLY SENTENCE FOR EXAMPLES.'
# Because a string is an instance of the str class, methods can also be called on them "directly".
>>> start_text = "my silly sentence for examples."
>>> start_text.upper() # <--Calling the upper() method on start_text directly.
'MY SILLY SENTENCE FOR EXAMPLES.'
# Alternatively, we can skip the variable assignment (although this gets messy quick).
>>> "my silly sentence for examples.".upper()
'MY SILLY SENTENCE FOR EXAMPLES.'
# Importing the math module
>>> import math
>>> math.pow(2,4) # <--Calling the pow() function from the math module.
16.0
Pythonのコメントは、文字列の一部ではない#で始まり、行の終わりで終わります。
他の多くのプログラミング言語と違い、Pythonは複数行コメントの記号をサポートしていません。
コメントブロックの各行は、#文字で始める必要があります。
コメントはインタプリターには無視されます。
# This is a single line comment.
x = "foo" # This is an in-line comment.
# This is a multi-line
# comment block over multiple lines --
# these should be used sparingly.
関数本体の最初の文は、任意でドキュメント文字列にできます。これは、関数やオブジェクトの目的を簡潔にまとめたものです。
ドキュメント文字列は、コードブロックと同じレベルにインデントした三重引用符(""")で宣言します。
# An example from PEP257 of a multi-line docstring
# reformatted to use Google style non-type hinted docstrings.
# Some additional details can be found in the Sphinx documentation:
# https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html#getting-started
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword Arguments:
real (float): The real part of the number (default 0.0)
imag (float): The imaginary part of the number (default 0.0)
"""
if imag == 0.0 and real == 0.0:
return complex_zero
ドキュメント文字列は自動ドキュメントツールに読み取られ、関数・メソッド・クラス名に対して特別な属性.__doc__を呼び出すと返されます。
ドキュメントが必要な規模を問わず、どんなプログラムでも推奨されており、その規約はPEP257に示されています。
ドキュメント文字列は軽量な単体テストとしても機能し、PyTestやdoctestモジュールをインポートすることで読み取って実行できます。
テストとdoctestは、後のコンセプトで扱います。
# An example on a user-defined function using a Google style docstring.
>>> def raise_to_power(number, power):
"""Raise a number to an arbitrary power.
Parameters:
number (int): The base number.
power (int): The power to raise the base number to.
Returns:
int: The number raised to the specified power.
Takes a number and raises it to the specified power, returning the result.
"""
return number ** power
...
# Calling the .__doc__ attribute of the function and printing the result.
>>> print(raise_to_power.__doc__)
Raise a number to an arbitrary power.
Parameters:
number (int): The base number.
power (int): The power to raise the base number to.
Returns:
int: The number raised to the specified power.
Takes a number and raises it to the specified power, returning the result.
...
# Printing the __doc__ attribute of the built-in type: str.
>>> print(str.__doc__)
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to 'utf-8'.
errors defaults to 'strict'.