Python/組込み関数
組込み関数 編集
Pythonインタープリターには、常に利用可能な関数や型がいくつか組込まれています。
組込み関数の一覧 編集
- 組込み関数の一覧を得るスクリプト
for x in (name for name in (dir(__builtins__)) if callable(getattr(__builtins__, name))): a = getattr(__builtins__, x) if a.__doc__ == None: continue print(x, a.__doc__.splitlines()[0], sep=": ")
- 実行例
ArithmeticError: Base class for arithmetic errors. AssertionError: Assertion failed. AttributeError: Attribute not found. BaseException: Common base class for all exceptions BlockingIOError: I/O operation would block. BrokenPipeError: Broken pipe. BufferError: Buffer error. BytesWarning: Base class for warnings about bytes and buffer related problems, mostly ChildProcessError: Child process error. ConnectionAbortedError: Connection aborted. ConnectionError: Connection error. ConnectionRefusedError: Connection refused. ConnectionResetError: Connection reset. DeprecationWarning: Base class for warnings about deprecated features. EOFError: Read beyond end of file. EnvironmentError: Base class for I/O related errors. Exception: Common base class for all non-exit exceptions. FileExistsError: File already exists. FileNotFoundError: File not found. FloatingPointError: Floating point operation failed. FutureWarning: Base class for warnings about constructs that will change semantically GeneratorExit: Request that a generator exit. IOError: Base class for I/O related errors. ImportError: Import can't find module, or can't find name in module. ImportWarning: Base class for warnings about probable mistakes in module imports IndentationError: Improper indentation. IndexError: Sequence index out of range. InterruptedError: Interrupted by signal. IsADirectoryError: Operation doesn't work on directories. KeyError: Mapping key not found. KeyboardInterrupt: Program interrupted by user. LookupError: Base class for lookup errors. MemoryError: Out of memory. ModuleNotFoundError: Module not found. NameError: Name not found globally. NotADirectoryError: Operation only works on directories. NotImplementedError: Method or function hasn't been implemented yet. OSError: Base class for I/O related errors. OverflowError: Result too large to be represented. PendingDeprecationWarning: Base class for warnings about features which will be deprecated PermissionError: Not enough permissions. ProcessLookupError: Process not found. RecursionError: Recursion limit exceeded. ReferenceError: Weak ref proxy used after referent went away. ResourceWarning: Base class for warnings about resource usage. RuntimeError: Unspecified run-time error. RuntimeWarning: Base class for warnings about dubious runtime behavior. StopAsyncIteration: Signal the end from iterator.__anext__(). StopIteration: Signal the end from iterator.__next__(). SyntaxError: Invalid syntax. SyntaxWarning: Base class for warnings about dubious syntax. SystemError: Internal error in the Python interpreter. SystemExit: Request to exit from the interpreter. TabError: Improper mixture of spaces and tabs. TimeoutError: Timeout expired. TypeError: Inappropriate argument type. UnboundLocalError: Local name referenced but not bound to a value. UnicodeDecodeError: Unicode decoding error. UnicodeEncodeError: Unicode encoding error. UnicodeError: Unicode related error. UnicodeTranslateError: Unicode translation error. UnicodeWarning: Base class for warnings about Unicode related problems, mostly UserWarning: Base class for warnings generated by user code. ValueError: Inappropriate argument value (of correct type). Warning: Base class for warning categories. ZeroDivisionError: Second argument to a division or modulo operation was zero. __build_class__: __build_class__(func, name, /, *bases, [metaclass], **kwds) -> class __import__: __import__(name, globals=None, locals=None, fromlist=(), level=0) -> module __loader__: Meta path import for built-in modules. abs: Return the absolute value of the argument. all: Return True if bool(x) is True for all values x in the iterable. any: Return True if bool(x) is True for any x in the iterable. ascii: Return an ASCII-only representation of an object. bin: Return the binary representation of an integer. bool: bool(x) -> bool breakpoint: breakpoint(*args, **kws) bytearray: bytearray(iterable_of_ints) -> bytearray bytes: bytes(iterable_of_ints) -> bytes callable: Return whether the object is callable (i.e., some kind of function). chr: Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. classmethod: classmethod(function) -> method compile: Compile source into a code object that can be executed by exec() or eval(). complex: Create a complex number from a real part and an optional imaginary part. copyright: interactive prompt objects for printing the license text, a list of credits: interactive prompt objects for printing the license text, a list of delattr: Deletes the named attribute from the given object. dict: dict() -> new empty dictionary dir: dir([object]) -> list of strings divmod: Return the tuple (x//y, x%y). Invariant: div*y + mod == x. enumerate: Return an enumerate object. eval: Evaluate the given source in the context of globals and locals. exec: Execute the given source in the context of globals and locals. filter: filter(function or None, iterable) --> filter object float: Convert a string or number to a floating point number, if possible. format: Return value.__format__(format_spec) frozenset: frozenset() -> empty frozenset object getattr: getattr(object, name[, default]) -> value globals: Return the dictionary containing the current scope's global variables. hasattr: Return whether the object has an attribute with the given name. hash: Return the hash value for the given object. help: Define the builtin 'help'. hex: Return the hexadecimal representation of an integer. id: Return the identity of an object. input: Read a string from standard input. The trailing newline is stripped. int: int([x]) -> integer isinstance: Return whether an object is an instance of a class or of a subclass thereof. issubclass: Return whether 'cls' is a derived from another class or is the same class. iter: iter(iterable) -> iterator len: Return the number of items in a container. license: interactive prompt objects for printing the license text, a list of list: Built-in mutable sequence. locals: Return a dictionary containing the current scope's local variables. map: map(func, *iterables) --> map object max: max(iterable, *[, default=obj, key=func]) -> value memoryview: Create a new memoryview object which references the given object. min: min(iterable, *[, default=obj, key=func]) -> value next: next(iterator[, default]) object: The base class of the class hierarchy. oct: Return the octal representation of an integer. open: Open file and return a stream. Raise OSError upon failure. ord: Return the Unicode code point for a one-character string. pow: Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments print: print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) property: Property attribute. range: range(stop) -> range object repr: Return the canonical string representation of the object. reversed: Return a reverse iterator over the values of the given sequence. round: Round a number to a given precision in decimal digits. set: set() -> new empty set object setattr: Sets the named attribute on the given object to the specified value. slice: slice(stop) sorted: Return a new list containing all items from the iterable in ascending order. staticmethod: staticmethod(function) -> method str: str(object='') -> str sum: Return the sum of a 'start' value (default: 0) plus an iterable of numbers super: super() -> same as super(__class__, <first argument>) tuple: Built-in immutable sequence. type: type(object_or_name, bases, dict) vars: vars([object]) -> dictionary zip: zip(*iterables) --> A zip object yielding tuples until an input is exhausted.
一覧 編集
abs 編集
組込み関数 abs(x) は x の絶対値を返します[1]。
- 関数定義
def abs(n):
- 引数nの型による動作の違い
-
- 整数
- xが負の値なら -x を、そうでなければ x を返します。
- 浮動書数点数
- xが NaN なら NaN を、負の値なら -x を、そうでなければ x を返します。
- 複素数
- 実数部と虚数部の自乗和の平方根を返します。実数部・虚数部のいずれかが NaN の場合は NaN+NaNj を返します。
- メソッド __abs__ を持つクラスのインスタンス
- メソッド __abs__ を呼出しその値を返します。
- コード例
print(abs(12)) print(abs(-42)) print(abs(3.14)) print(abs(-2.73)) print(abs(+0.0)) print(abs(-0.0)) print(abs(2+2j)) print(abs(-3+-4j)) class AbsTest : def __init__(self, x) : self._x = x def __abs__(self) : return f"ABS({self._x})" x = AbsTest(-12) print(abs(x))
- 実行結果
12 42 3.14 2.73 0.0 0.0 2.8284271247461903 5.0 ABS(-12)
aiter 編集
Pythonの aiter
は非同期イテレータを作成するための関数です。これは非同期イテラブルの要素を一度に一つずつ取得するための機能を提供します[2]。
非同期イテレータは、非同期ジェネレータ関数で作成されることが一般的です。非同期ジェネレータは async def
の形式で作成され、yield
の代わりに yield
の非同期版である await yield
を使用します。
例えば、以下は非同期イテレータの例です:
async def my_async_iterator(): yield 1 yield 2 yield 3 # 非同期イテレータを作成 ait = my_async_iterator() # イテレータから値を取得 value = await ait.__anext__() print(value) # 出力: 1 value = await ait.__anext__() print(value) # 出力: 2 value = await ait.__anext__() print(value) # 出力: 3
aiter
は通常、非同期イテレータを作成するためのショートカットとして使用されます。例えば:
async def my_async_iterator(): yield 1 yield 2 yield 3 # 非同期イテレータを作成 ait = aiter(my_async_iterator()) # イテレータから値を取得 value = await ait.__anext__() print(value) # 出力: 1 value = await ait.__anext__() print(value) # 出力: 2 value = await ait.__anext__() print(value) # 出力: 3
aiter
は、非同期イテレータの一部として、非同期処理におけるデータの非同期的な取得を可能にします。
all 編集
組込み関数 all(it) は、iterableオブジェクトitの要素がすべて真のときにTrueを返し、1つでも偽があればFalseを返します[3]。
- 関数定義
def all(it: Iterable) -> bool:
- コード例
print(f"""\ list: {type([])=} {all([True, True, True])=} {all([True, True, False])=} {all([])=} tuple: {type(())=} {all((True, True, True))=} {all((True, True, False))=} {all(())=} range: {type(range(0))=} {all(range(5))=} {all(range(5,2))=} {all(range(0))=} set: {type(set())=} {all({True, 1,"x"})=} {all({True, 1, "x", False})=} {all(set())=} dict: {type({})=} {all({1:True, 2:1, 3:"x"})=} {all({1:True, 2:1, 3:"x", 0:123})=} {all({})=} str: {type("")=} {all("abc")=} {all("True")=} {all("False")=} {all("")=} """)
- 実行結果
list: type([])=<class 'list'> all([True, True, True])=True all([True, True, False])=False all([])=True tuple: type(())=<class 'tuple'> all((True, True, True))=True all((True, True, False))=False all(())=True range: type(range(0))=<class 'range'> all(range(5))=False all(range(5,2))=True all(range(0))=True set: type(set())=<class 'set'> all({True, 1,"x"})=True all({True, 1, "x", False})=False all(set())=True dict: type({})=<class 'dict'> all({1:True, 2:1, 3:"x"})=True all({1:True, 2:1, 3:"x", 0:123})=False all({})=True str: type("")=<class 'str'> all("abc")=True all("True")=True all("False")=True all("")=True
anext 編集
anext()
メソッドは非同期イテレータの次の値を取得するために使用されます。非同期イテレータは非同期ジェネレータ関数から作成され、非同期処理の流れを制御しながら一度に一つずつ値を返すことができます[4]。
この anext()
メソッドは通常、非同期ジェネレータから作成された非同期イテレータを操作するために使用されます。await
キーワードを用いて anext()
を呼び出し、非同期イテレータから次の値を取得します。
例えば、次のような非同期イテレータを考えてみましょう:
async def my_async_iterator(): yield 1 yield 2 yield 3 # 非同期イテレータを作成 ait = my_async_iterator() # イテレータから値を取得 value = await ait.__anext__() print(value) # 出力: 1 value = await ait.__anext__() print(value) # 出力: 2 value = await ait.__anext__() print(value) # 出力: 3
上記の例では、非同期イテレータから anext()
を使用して値を取り出し、それを表示しています。このようにして、anext()
を使用することで非同期イテレータから次の値を非同期的に取得できます。
any 編集
組込み関数 any(it) は、iterableオブジェクトitの要素がすべて偽のときにFalseを返し、1つでも真があればTrueを返します[5]。
- 関数定義
def any(it: Iterable) -> bool:
- コード例
# list print(type([])) print(any([True, True, True])) print(any([True, True, False])) print(any([False, False, False])) print(any([])) # tuple print(type(())) print(any((True, True, True))) print(any((True, True, False))) print(any((False, False, False))) print(any(())) # range print(range((0))) print(any(range(5))) print(any(range(5,2))) print(any(range(0))) # set print(type(set())) print(any({True, 1,"x"})) print(any({True, 1, "x", False})) print(any({False, 0})) print(any(set())) # dict print(type({})) print(any({1:True, 2:1, 3:"x"})) print(any({1:True, 2:1, 3:"x", 0:123})) print(any({False:12, 0:34})) print(any({})) # str print(type("")) print(any("abc")) print(any("True")) print(any("False")) print(any(""))
- 実行結果
<class 'list'> True True False False <class 'tuple'> True True False False range(0, 0) True False False <class 'set'> True True False False <class 'dict'> True True False False <class 'str'> True True True False
ascii 編集
組込み関数 ascii(obj) は、組込み関数 repr(obj) と同様に,オブジェクトobjの印刷可能な表現を含む文字列を返しますが,repr()が返す文字列中の非ASCII文字を,\x, \u, \Uを用いてエスケープします[6]。
- 関数定義
def ascii(obj: Any) -> str:
- コード例
print(ascii("")) print(ascii("abcABC1213#$")) print(ascii("かなカナ漢字αβ")) print(ascii((1, 2.0, "III", "四"))) print(ascii({1, 2.0, "III", "四"})) print(ascii({0:1, 2:2.0, 3:"III", 4:"四"}))
- 実行結果
'' 'abcABC1213#$' '\u304b\u306a\u30ab\u30ca\u6f22\u5b57\u03b1\u03b2' (1, 2.0, 'III', '\u56db') {1, 2.0, '\u56db', 'III'} {0: 1, 2: 2.0, 3: 'III', 4: '\u56db'}
bin 編集
組込み関数bin(i)は、整数iを2進数文字列に変換します[7]。
- 関数定義
def bin(i: int) -> str:
- コード例
for i in range(-2,0o10) : print(f"bin({i}) => {repr(bin(i))}") for i in [False, True] : print(f"bin({i}) => {repr(bin(i))}")
- 実行結果
bin(-2) => '-0b10' bin(-1) => '-0b1' bin(0) => '0b0' bin(1) => '0b1' bin(2) => '0b10' bin(3) => '0b11' bin(4) => '0b100' bin(5) => '0b101' bin(6) => '0b110' bin(7) => '0b111' bin(False) => '0b0' bin(True) => '0b1'
- 変換結果には2進数を示す '0b' が前置されます。
- この表現は Python の2進数リテラルと同じ表記です。
- 負の値は、2の補数表現ではなく 絶対値の2進数表現に '-' を前置して表現します。
- bool型はint型のサブクラスなので、bin()関数を適用できます。
bool 編集
組込み関数bool(obj)は、オブジェクトobjを真理値に変換します[8]。
- 関数定義
def bool(obj: Any) -> bool:
- オブジェクトの属するクラスにメソッド __bool__ があった場合、メソッド __bool__ を評価しその値を返します。
- オブジェクトの属するクラスにメソッド __len__ があった場合、メソッド __len__ を評価しその値が 0 以外なら True を返します。
- 典型的な偽の数
from decimal import Decimal from fractions import Fraction for x in [None, False, 0, 0.0, 0j, Decimal(0), Fraction(0, 1), '', (), [], {}, set(), range(0)] : print(f"bool({repr(x)}) => {bool(x)}")
- 実行結果
bool(None) => False bool(False) => False bool(0) => False bool(0.0) => False bool(0j) => False bool(Decimal('0')) => False bool(Fraction(0, 1)) => False bool('') => False bool(()) => False bool([]) => False bool({}) => False bool(set()) => False bool(range(0, 0)) => False
- Decimalは十進浮動書数点数、Fractionは有理数(分数)です。
breakpoint 編集
bytearray 編集
bytes 編集
callable 編集
組込み関数callable(obj)は、オブジェクトobjが呼出し可能かを返します[9]。
- 関数定義
def callable(obj: Any) -> bool:
- オブジェクトの属するクラスにメソッド __call__ があった場合、True を返します。
- callableの適用例
print(f"""\ {callable(int)=} {callable(bool)=} {callable(str)=} {callable(True)=} {callable([])=} {callable(set())=} {callable("abc".join)=} {callable((1+1j).conjugate)=} """)
- 実行結果
callable(int)=True callable(bool)=True callable(str)=True callable(True)=False callable([])=False callable(set())=False callable("abc".join)=True callable((1+1j).conjugate)=True
- 型名はコンストラクターでcallableです。
- メソッドもcallableです。
chr 編集
classmethod 編集
compile 編集
complex 編集
copyright 編集
credits 編集
delattr 編集
dict 編集
dir 編集
divmod 編集
enumerate 編集
eval 編集
exec 編集
exit 編集
filter 編集
float 編集
組込み関数float(x, base)は、数値または文字列xから構成される浮動小数点数を返します[10]。
- 関数定義
def float(x=0: Any) -> float:
- 引数xが文字列の場合、文字列には10進数が含まれ、オプションで符号が先行し、オプションでホワイトスペースが埋め込まれます。
- オプションの符号は'+'または'-'ですが、'+'符号は生成される値には影響しません。
- また、引数には、NaN(not-a-number)、正または負の無限大を表す文字列を指定することもできます。
- より正確には,入力は,先頭と末尾の空白文字を除去した後,以下の文法に従わなければならない。
sign ::= "+" | "-" infinity ::= "Infinity" | "inf" nan ::= "nan" numeric_value ::= floatnumber | infinity | nan numeric_string ::= [sign] numeric_value
- ここで floatnumber は、浮動小数点リテラルで説明されている Python の浮動小数点リテラルの形式です。
- 大文字小文字は区別されませんので、例えば、正の無限大を表すスペルとして、"inf"、"Inf"、"INFINITY"、"iNfINity "は全て許容されます。
- その他、引数が整数または浮動小数点数の場合、同じ値の浮動小数点数(Pythonの浮動小数点精度の範囲内)が返されます。
- 一般的な Python オブジェクト x に対して、 float(x) は x.__float__() に委ねられます。
- もし __float__() が定義されていなければ、__index__() にフォールバックします。
- 引数が与えられていない場合は 0.0 が返されます。
- 例外
- 引数が Python の float の範囲外であれば、 OverflowError が発生します。
- バージョン3.6での変更
- コードリテラルのようにアンダースコアで数字をまとめることができるようになりました。
- バージョン3.7での変更
- x は位置指定のみのパラメータになりました。
- バージョン3.8での変更
- float__()が定義されていない場合、__index__()にフォールバックするようになりました。
format 編集
frozenset 編集
getattr 編集
globals 編集
hasattr 編集
hash 編集
help 編集
hex 編集
組込み関数hex(i)は、整数iを16進数文字列に変換します[11]。
- 関数定義
def hex(i: int) -> str:
- コード例
for i in range(-2,0x10) : print(f"hex({i}) => {repr(hex(i))}") for i in [False, True] : print(f"hex({i}) => {repr(hex(i))}")
- 実行結果
hex(-2) => '-0x2' hex(-1) => '-0x1' hex(0) => '0x0' hex(1) => '0x1' hex(2) => '0x2' hex(3) => '0x3' hex(4) => '0x4' hex(5) => '0x5' hex(6) => '0x6' hex(7) => '0x7' hex(8) => '0x8' hex(9) => '0x9' hex(10) => '0xa' hex(11) => '0xb' hex(12) => '0xc' hex(13) => '0xd' hex(14) => '0xe' hex(15) => '0xf' hex(False) => '0x0' hex(True) => '0x1'
- 変換結果には2進数を示す '0x' が前置されます。
- この表現は Python の16進数リテラルと同じ表記です。
- 負の値は、2の補数表現ではなく 絶対値の16進数表現に '-' を前置して表現します。
- bool型はint型のサブクラスなので、hex()関数を適用できます。
id 編集
input 編集
組込み関数input(prompt)は、標準入力から1行を読込み、それを文字列に変換して(末尾の改行を取り除いて)返します[12]。
- 関数定義
def input(prompt: str) -> Any:
- prompt 引数がある場合は、末尾の改行を除いて標準出力に書込まれます。
- モジュールreadlineがロードされていれば、input()はそれを使って精巧な行編集や履歴機能を提供します。
- 例外
- EOFを読み込んだ場合、EOFErrorが発生します。
- 入力を読込み前に、prompt 引数の値によっては、で監査イベント(auditing event)builtins.inputを発生させます。
- 入力を読込み後に、返数値によっては、で監査イベントbuiltins.input/resultを発生させます。
int 編集
組込み関数int(x, base)は、引数xを基数baseで整数に変換します[13]。
- 関数定義
def int(x=0: Any, base=10: int) -> int:
- 数値または文字列xから構築された整数オブジェクトを返します。
- 引数が与えられていない場合は0を返します。
- xが__int__()を定義している場合、int(x)はx.__int__()を返します。
- xが__index__()を定義している場合は、x.__index__()を返します。
- xが__trunc__()を定義している場合は、x.__trunc__()を返します。
- xが浮動小数点数の場合、これはゼロに向かって切り捨てられます。
- xが数値でない場合、またはbaseが指定されている場合、xは基数ベースの整数リテラルを表す文字列、バイト、またはバイト配列のインスタンスでなければなりません。
- オプションとして、リテラルの前に+または-(間にスペースを入れない)を付け、ホワイトスペースで囲むことができます。基数baseのリテラルは、0からn-1までの数字で構成され、aからz(またはAからZ)は10から35までの値を持ちます。
- デフォルトのbaseは10です。
- 許容される値は0と2-36です。
- 基数2、-8、-16のリテラルには、コードの整数リテラルと同様に、0b/0B、0o/0O、0x/0Xのいずれかのプレフィックスを付けることができます。
- 基数0はコードリテラルとして正確に解釈することを意味し、実際の基数は2、8、10、16のいずれかであり、int('010', 0)は合法ではないが、int('010')は合法であり、int('010', 8)も同様です。
- バージョン3.4での変更
- baseがintのインスタンスではなく、baseオブジェクトにbase.__index__メソッドがある場合、そのメソッドが呼び出されてbaseの整数値が取得されます。以前のバージョンでは base.__index__ の代わりに base.__int__ を使用していました。
- バージョン3.6での変更
- コードリテラルのように数字をアンダースコアでまとめることができるようになりました。
- バージョン3.7での変更
- x は位置指定のみのパラメータになりました。
- バージョン3.8での変更
- __int__()が定義されていない場合、__index__()に戻るようになりました。
isinstance 編集
issubclass 編集
iter 編集
len 編集
license 編集
list 編集
locals 編集
map 編集
max 編集
memoryview 編集
min 編集
next 編集
object 編集
oct 編集
組込み関数oct(i)は、整数iを8進数文字列に変換します[14]。
- 関数定義
def oct(i: int) -> str:
- コード例
for i in range(-2,0o10) : print(f"{i=}: {oct(i)=}") for i in [False, True] : print(f"{i=}: {oct(i)=}")
- 実行結果
i=-2: oct(i)='-0o2' i=-1: oct(i)='-0o1' i=0: oct(i)='0o0' i=1: oct(i)='0o1' i=2: oct(i)='0o2' i=3: oct(i)='0o3' i=4: oct(i)='0o4' i=5: oct(i)='0o5' i=6: oct(i)='0o6' i=7: oct(i)='0o7' i=False: oct(i)='0o0' i=True: oct(i)='0o1'
- 変換結果には2進数を示す '0o' が前置されます(古いC言語の '0' 1文字を前置する8進数表現ではありません)。
- この表現は Python の8進数リテラルと同じ表記です。
- 負の値は、2の補数表現ではなく 絶対値の8進数表現に '-' を前置して表現します。
- bool型はint型のサブクラスなので、oct()関数を適用できます。
open 編集
ord 編集
pow 編集
組込み関数 pow は累乗を返します[15]。
modが存在する場合、baseをmodulo modのexp乗にします(pow(base, exp) % modよりも効率的に計算されます)。2つの引数形式pow(base, exp)はべき乗演算子の使用と同等です: base**exp。
引数は数値型でなければなりません。オペランドの型が混在する場合、二項演算子の強制適用規則が適用される。int 型のオペランドでは、2 番目の引数が負でない限り、結果はオペランドと同じ型になります(強制適用後)。たとえば、pow(10, 2)は100を返しますが、pow(10, -2)は0.01を返します。int型またはfloat型の負の基数と非積分指数に対しては、複素数の結果が返されます。例えば、pow(-9, 0.5)は3jに近い値を返します。
int 型のオペランド base および exp に対しては、mod が存在する場合、mod も整数型でなければならず、mod は 0 以外でなければなりません。modが存在し、expが負の場合、baseはmodに対して相対的に素でなければなりません。この場合、pow(inv_base, -exp, mod) が返され、inv_base は base の mod の逆数です。
- 関数定義
number = int | float | complex def pow(base: number, exp: number[, mod: number])
- 引数
-
- base
- 基数
- exp
- 指数
- mod
- 除数
print 編集
組込み関数 print は引数のオブジェクトを文字列化しテキストストリームに書出します[16]。
- 関数定義
def print(*objects: Any, sep=' ', end='\n', file=sys.stdout, flush=False) -> None:
- 引数
-
- objects
- str関数相当で文字列化されるオブジェクト
- sep
- objectsの間に表示する区切り文字
- file
- 出力先のテキストストリーム(ディフォルト:sys.stdout)
- flush
- フラッシュの有無(ディフォルト:False)
property 編集
quit 編集
range 編集
組込み関数 range() は、組込み型 Range クラスのコンストラクターです[17][18]。
- 関数定義
def range(stop: int) -> range: def range(start : int, stop: int[, step]) -> range:
- 引数は整数でなければなりません (組込みの int または __index__ 特殊メソッドを実装したオブジェクトのいずれか)。
- step 引数
- 省略された場合、デフォルトで 1 になります。
- start 引数
- が省略された場合、デフォルトで 0 になります。
- step 引数
-
- 0 の場合
- ValueError 例外が挙がります。
- 正の場合
- Range rの内容はr[i] = start + step*iの式で決まり、i >= 0 and r[i] < stopとなります。
- 負の場合
- Range rの内容はr[i] = start + step*iの式で決まり、i >= 0 and r[i] > stopとなります。
- r[0]が値の制約を満たさない場合、Rangeオブジェクトは空になります。
- Rangeは負のインデックスをサポートしていますが、これらは正のインデックスによって決定されたシーケンスの最後からインデックスを作成すると解釈されます。
- sys.maxsizeより大きな絶対値を含むレンジは許可されていますが、いくつかの機能(len()など)はOverflowErrorが挙がる可能性があります。
- コード例
for i in range(5) : print(i, end=" ") else : print() for i in range(2, 12, 3) : print(i, end=" ") else : print() print(list(range(10))) print(tuple(range(10))) n = 10**8 print(n) print(sum(range(n))) print(type(range(5)))
- 実行結果
0 1 2 3 4 2 5 8 11 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) 100000000 4999999950000000 <class 'range'>
repr 編集
組込み関数 repr(obj) は、オブジェクトobjの印刷可能な表現を含む文字列を返します[19]。
- 関数定義
def repr(obj: ANy) -> str:
- コード例
print(repr("")) print(repr("abcABC1213#$")) print(repr("かなカナ漢字αβ")) print(repr((1, 2.0, "III", "四"))) print(repr({1, 2.0, "III", "四"})) print(repr({0:1, 2:2.0, 3:"III", 4:"四"}))
- 実行結果
'' 'abcABC1213#$' 'かなカナ漢字αβ' (1, 2.0, 'III', '四') {'四', 1, 2.0, 'III'} {0: 1, 2: 2.0, 3: 'III', 4: '四'}
reversed 編集
round 編集
set 編集
setattr 編集
slice 編集
sorted 編集
staticmethod 編集
str 編集
sum 編集
super 編集
tuple 編集
type 編集
vars 編集
zip 編集
脚註 編集
- ^ “Built-in Functions -- abs()”. The Python Standard Library (2021年11月15日). 2021年11月16日閲覧。
- ^ “Built-in Functions -- aiter()”. The Python Standard Library (2023年11月29日). 2023年12月1日閲覧。
- ^ “Built-in Functions -- all()”. The Python Standard Library (2021年11月15日). 2021年11月16日閲覧。
- ^ “Built-in Functions -- anext()”. The Python Standard Library (2023年11月29日). 2023年12月1日閲覧。
- ^ “Built-in Functions -- any()”. The Python Standard Library (2021年11月15日). 2021年11月16日閲覧。
- ^ “Built-in Functions -- ascii()”. The Python Standard Library (2021年11月15日). 2021年11月16日閲覧。
- ^ “Built-in Functions -- bin()”. The Python Standard Library (2021年11月15日). 2021年11月16日閲覧。
- ^ “Built-in Functions -- bool()”. The Python Standard Library (2021年11月15日). 2021年11月16日閲覧。
- ^ “Built-in Functions -- callable()”. The Python Standard Library (2021年12月19日). 2021年12月20日閲覧。
- ^ “Built-in Functions -- float()”. The Python Standard Library (2021年12月13日). 2021年12月14日閲覧。
- ^ “Built-in Functions -- hex()”. The Python Standard Library (2021年11月15日). 2021年11月16日閲覧。
- ^ “Built-in Functions -- input()”. The Python Standard Library (2021年12月13日). 2021年12月14日閲覧。
- ^ “Built-in Functions -- int()”. The Python Standard Library (2021年12月13日). 2021年12月14日閲覧。
- ^ “Built-in Functions -- oct()”. The Python Standard Library (2021年11月15日). 2021年11月16日閲覧。
- ^ “Built-in Functions -- pow()”. The Python Standard Library (2022年10月16日). 2022年10月16日閲覧。
- ^ “Built-in Functions -- print()”. The Python Standard Library (2021年11月15日). 2021年11月16日閲覧。
- ^ “Built-in Functions -- range()”. The Python Standard Library (2021年11月15日). 2021年11月19日閲覧。
- ^ “Built-in Types -- Ranges”. The Python Standard Library (2021年11月15日). 2021年11月19日閲覧。
- ^ “Built-in Functions -- repr()”. The Python Standard Library (2021年11月15日). 2021年11月16日閲覧。