# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001 Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # python-doc bot, 2025 # TENMYO Masakazu, 2025 # Takanori Suzuki , 2026 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.14\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2026-04-17 14:50+0000\n" "PO-Revision-Date: 2025-09-16 00:02+0000\n" "Last-Translator: Takanori Suzuki , 2026\n" "Language-Team: Japanese (https://app.transifex.com/python-doc/teams/5390/" "ja/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ja\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../tutorial/controlflow.rst:5 msgid "More Control Flow Tools" msgstr "その他の制御フローツール" #: ../../tutorial/controlflow.rst:7 msgid "" "As well as the :keyword:`while` statement just introduced, Python uses a few " "more that we will encounter in this chapter." msgstr "" "前章で紹介した :keyword:`while` 文の他にも、 Python にはいくつか制御フロー" "ツールがあり、本章で説明します。" #: ../../tutorial/controlflow.rst:14 msgid ":keyword:`!if` Statements" msgstr ":keyword:`!if` 文" #: ../../tutorial/controlflow.rst:16 msgid "" "Perhaps the most well-known statement type is the :keyword:`if` statement. " "For example::" msgstr "おそらく最もおなじみの文型は :keyword:`if` 文でしょう。例えば::" #: ../../tutorial/controlflow.rst:19 msgid "" ">>> x = int(input(\"Please enter an integer: \"))\n" "Please enter an integer: 42\n" ">>> if x < 0:\n" "... x = 0\n" "... print('Negative changed to zero')\n" "... elif x == 0:\n" "... print('Zero')\n" "... elif x == 1:\n" "... print('Single')\n" "... else:\n" "... print('More')\n" "...\n" "More" msgstr "" ">>> x = int(input(\"Please enter an integer: \"))\n" "Please enter an integer: 42\n" ">>> if x < 0:\n" "... x = 0\n" "... print('Negative changed to zero')\n" "... elif x == 0:\n" "... print('Zero')\n" "... elif x == 1:\n" "... print('Single')\n" "... else:\n" "... print('More')\n" "...\n" "More" #: ../../tutorial/controlflow.rst:33 msgid "" "There can be zero or more :keyword:`elif` parts, and the :keyword:`else` " "part is optional. The keyword ':keyword:`!elif`' is short for 'else if', " "and is useful to avoid excessive indentation. An :keyword:`!if` ... :" "keyword:`!elif` ... :keyword:`!elif` ... sequence is a substitute for the " "``switch`` or ``case`` statements found in other languages." msgstr "" "ゼロ個以上の :keyword:`elif` 部を使うことができ、 :keyword:`else` 部を付ける" "こともできます。キーワード ':keyword:`!elif`' は 'else if' を短くしたもので、" "過剰なインデントを避けるのに役立ちます。一連の :keyword:`!if` ... :keyword:`!" "elif` ... :keyword:`!elif` ... は、他の言語における ``switch`` 文や " "``case`` 文の代用となります。" #: ../../tutorial/controlflow.rst:39 msgid "" "If you're comparing the same value to several constants, or checking for " "specific types or attributes, you may also find the :keyword:`!match` " "statement useful. For more details see :ref:`tut-match`." msgstr "" "いくつかの定数と同じ値かを比較する場合や、特定の型や属性かを確認する場合に" "は、:keyword:`!match` 文が便利です。詳細は :ref:`tut-match` を参照してくださ" "い。" #: ../../tutorial/controlflow.rst:46 msgid ":keyword:`!for` Statements" msgstr ":keyword:`!for` 文" #: ../../tutorial/controlflow.rst:51 msgid "" "The :keyword:`for` statement in Python differs a bit from what you may be " "used to in C or Pascal. Rather than always iterating over an arithmetic " "progression of numbers (like in Pascal), or giving the user the ability to " "define both the iteration step and halting condition (as C), Python's :" "keyword:`!for` statement iterates over the items of any sequence (a list or " "a string), in the order that they appear in the sequence. For example (no " "pun intended):" msgstr "" "Python の :keyword:`for` 文は、読者が C 言語や Pascal 言語で使いなれているか" "もしれない :keyword:`for` 文とは少し違います。 (Pascal のように) 常に算術型の" "数列にわたる反復を行ったり、 (C のように) 繰返しステップと停止条件を両方とも" "ユーザが定義できるようにするのとは違い、Python の :keyword:`!for` 文は、任意" "のシーケンス型 (リストまたは文字列) にわたって反復を行います。反復の順番は" "シーケンス中に要素が現れる順番です。例えば:" #: ../../tutorial/controlflow.rst:63 msgid "" ">>> # Measure some strings:\n" ">>> words = ['cat', 'window', 'defenestrate']\n" ">>> for w in words:\n" "... print(w, len(w))\n" "...\n" "cat 3\n" "window 6\n" "defenestrate 12" msgstr "" ">>> # 文字列の長さを計測:\n" ">>> words = ['cat', 'window', 'defenestrate']\n" ">>> for w in words:\n" "... print(w, len(w))\n" "...\n" "cat 3\n" "window 6\n" "defenestrate 12" #: ../../tutorial/controlflow.rst:72 msgid "" "Code that modifies a collection while iterating over that same collection " "can be tricky to get right. Instead, it is usually more straight-forward to " "loop over a copy of the collection or to create a new collection::" msgstr "" "コレクションオブジェクトの値を反復処理をしているときに、そのコレクションオブ" "ジェクトを変更するコードは理解するのが面倒になり得ます。\n" "そうするよりも、コレクションオブジェクトのコピーに対して反復処理をするか、新" "しいコレクションオブジェクトを作成する方が通常は理解しやすいです::" #: ../../tutorial/controlflow.rst:76 msgid "" "# Create a sample collection\n" "users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}\n" "\n" "# Strategy: Iterate over a copy\n" "for user, status in users.copy().items():\n" " if status == 'inactive':\n" " del users[user]\n" "\n" "# Strategy: Create a new collection\n" "active_users = {}\n" "for user, status in users.items():\n" " if status == 'active':\n" " active_users[user] = status" msgstr "" "# コレクション作成\n" "users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}\n" "\n" "# 方針: コピーを反復\n" "for user, status in users.copy().items():\n" " if status == 'inactive':\n" " del users[user]\n" "\n" "# 方針: 新コレクション作成\n" "active_users = {}\n" "for user, status in users.items():\n" " if status == 'active':\n" " active_users[user] = status" #: ../../tutorial/controlflow.rst:94 msgid "The :func:`range` Function" msgstr ":func:`range` 関数" #: ../../tutorial/controlflow.rst:96 msgid "" "If you do need to iterate over a sequence of numbers, the built-in function :" "func:`range` comes in handy. It generates arithmetic progressions::" msgstr "" "数列にわたって反復を行う必要がある場合、組み込み関数 :func:`range` が便利で" "す。この関数は算術型の数列を生成します::" #: ../../tutorial/controlflow.rst:99 msgid "" ">>> for i in range(5):\n" "... print(i)\n" "...\n" "0\n" "1\n" "2\n" "3\n" "4" msgstr "" ">>> for i in range(5):\n" "... print(i)\n" "...\n" "0\n" "1\n" "2\n" "3\n" "4" #: ../../tutorial/controlflow.rst:108 msgid "" "The given end point is never part of the generated sequence; ``range(10)`` " "generates 10 values, the legal indices for items of a sequence of length " "10. It is possible to let the range start at another number, or to specify " "a different increment (even negative; sometimes this is called the 'step')::" msgstr "" "指定した終端値は生成されるシーケンスには入りません。``range(10)`` は 10 個の" "値を生成し、長さ 10 のシーケンスにおける各項目のインデクスとなります。range " "を別の数から開始したり、他の増加量 (負でも; 増加量は時に 'ステップ(step)' と" "呼ばれることもあります) を指定することもできます::" #: ../../tutorial/controlflow.rst:113 msgid "" ">>> list(range(5, 10))\n" "[5, 6, 7, 8, 9]\n" "\n" ">>> list(range(0, 10, 3))\n" "[0, 3, 6, 9]\n" "\n" ">>> list(range(-10, -100, -30))\n" "[-10, -40, -70]" msgstr "" ">>> list(range(5, 10))\n" "[5, 6, 7, 8, 9]\n" "\n" ">>> list(range(0, 10, 3))\n" "[0, 3, 6, 9]\n" "\n" ">>> list(range(-10, -100, -30))\n" "[-10, -40, -70]" #: ../../tutorial/controlflow.rst:122 msgid "" "To iterate over the indices of a sequence, you can combine :func:`range` " "and :func:`len` as follows::" msgstr "" "あるシーケンスにわたってインデクスで反復を行うには、 :func:`range` と :func:" "`len` を次のように組み合わせられます::" #: ../../tutorial/controlflow.rst:125 msgid "" ">>> a = ['Mary', 'had', 'a', 'little', 'lamb']\n" ">>> for i in range(len(a)):\n" "... print(i, a[i])\n" "...\n" "0 Mary\n" "1 had\n" "2 a\n" "3 little\n" "4 lamb" msgstr "" ">>> a = ['Mary', 'had', 'a', 'little', 'lamb']\n" ">>> for i in range(len(a)):\n" "... print(i, a[i])\n" "...\n" "0 Mary\n" "1 had\n" "2 a\n" "3 little\n" "4 lamb" #: ../../tutorial/controlflow.rst:135 msgid "" "In most such cases, however, it is convenient to use the :func:`enumerate` " "function, see :ref:`tut-loopidioms`." msgstr "" "しかし、多くの場合は :func:`enumerate` 関数を使う方が便利です。 :ref:`tut-" "loopidioms` を参照してください。" #: ../../tutorial/controlflow.rst:138 msgid "A strange thing happens if you just print a range::" msgstr "range を直接出力すると変なことになります::" #: ../../tutorial/controlflow.rst:140 msgid "" ">>> range(10)\n" "range(0, 10)" msgstr "" ">>> range(10)\n" "range(0, 10)" #: ../../tutorial/controlflow.rst:143 msgid "" "In many ways the object returned by :func:`range` behaves as if it is a " "list, but in fact it isn't. It is an object which returns the successive " "items of the desired sequence when you iterate over it, but it doesn't " "really make the list, thus saving space." msgstr "" ":func:`range` が返すオブジェクトは、いろいろな点でリストであるかのように振る" "舞いますが、本当はリストではありません。これは、イテレートした時に望んだ数列" "の連続した要素を返すオブジェクトです。しかし実際にリストを作るわけではないの" "で、スペースの節約になります。" #: ../../tutorial/controlflow.rst:148 msgid "" "We say such an object is :term:`iterable`, that is, suitable as a target for " "functions and constructs that expect something from which they can obtain " "successive items until the supply is exhausted. We have seen that the :" "keyword:`for` statement is such a construct, while an example of a function " "that takes an iterable is :func:`sum`::" msgstr "" "このようなオブジェクトは :term:`イテラブル ` と呼ばれます。\n" "これらは関数や構成物のターゲットとして、あるだけの項目を逐次与えるのに適して" "います。\n" ":keyword:`for` 文がそのような構成物であることはすでに見てきており、イテラブル" "を受け取る関数の例には :func:`sum` があります::" #: ../../tutorial/controlflow.rst:154 msgid "" ">>> sum(range(4)) # 0 + 1 + 2 + 3\n" "6" msgstr "" ">>> sum(range(4)) # 0 + 1 + 2 + 3\n" "6" #: ../../tutorial/controlflow.rst:157 msgid "" "Later we will see more functions that return iterables and take iterables as " "arguments. In chapter :ref:`tut-structures`, we will discuss :func:`list` " "in more detail." msgstr "" #: ../../tutorial/controlflow.rst:164 msgid ":keyword:`!break` and :keyword:`!continue` Statements" msgstr ":keyword:`!break` 文と :keyword:`!continue` 文" #: ../../tutorial/controlflow.rst:166 msgid "" "The :keyword:`break` statement breaks out of the innermost enclosing :" "keyword:`for` or :keyword:`while` loop::" msgstr "" ":keyword:`break` 文は、その `break` 文を内包している最も内側にある :keyword:" "`for` 文または :keyword:`while` 文から抜け出すことができます::" #: ../../tutorial/controlflow.rst:169 msgid "" ">>> for n in range(2, 10):\n" "... for x in range(2, n):\n" "... if n % x == 0:\n" "... print(f\"{n} equals {x} * {n//x}\")\n" "... break\n" "...\n" "4 equals 2 * 2\n" "6 equals 2 * 3\n" "8 equals 2 * 4\n" "9 equals 3 * 3" msgstr "" ">>> for n in range(2, 10):\n" "... for x in range(2, n):\n" "... if n % x == 0:\n" "... print(f\"{n} は {x} * {n//x} と等しい\")\n" "... break\n" "...\n" "4 は 2 * 2 と等しい\n" "6 は 2 * 3 と等しい\n" "8 は 2 * 4 と等しい\n" "9 は 3 * 3 と等しい" #: ../../tutorial/controlflow.rst:180 msgid "" "The :keyword:`continue` statement continues with the next iteration of the " "loop::" msgstr ":keyword:`continue` 文はループの次のイテレーションを実行します::" #: ../../tutorial/controlflow.rst:183 msgid "" ">>> for num in range(2, 10):\n" "... if num % 2 == 0:\n" "... print(f\"Found an even number {num}\")\n" "... continue\n" "... print(f\"Found an odd number {num}\")\n" "...\n" "Found an even number 2\n" "Found an odd number 3\n" "Found an even number 4\n" "Found an odd number 5\n" "Found an even number 6\n" "Found an odd number 7\n" "Found an even number 8\n" "Found an odd number 9" msgstr "" ">>> for num in range(2, 10):\n" "... if num % 2 == 0:\n" "... print(f\"偶数 {num} を見つけた\")\n" "... continue\n" "... print(f\"奇数 {num} を見つけた\")\n" "...\n" "偶数 2 を見つけた\n" "奇数 3 を見つけた\n" "偶数 4 を見つけた\n" "奇数 5 を見つけた\n" "偶数 6 を見つけた\n" "奇数 7 を見つけた\n" "偶数 8 を見つけた\n" "奇数 9 を見つけた" #: ../../tutorial/controlflow.rst:202 msgid ":keyword:`!else` Clauses on Loops" msgstr "ループの :keyword:`!else` 節" #: ../../tutorial/controlflow.rst:204 msgid "" "In a :keyword:`!for` or :keyword:`!while` loop the :keyword:`!break` " "statement may be paired with an :keyword:`!else` clause. If the loop " "finishes without executing the :keyword:`!break`, the :keyword:`!else` " "clause executes." msgstr "" ":keyword:`!for` または :keyword:`!while` ループ中の :keyword:`!break` 文は :" "keyword:`!else` 節と対になる場合があります。:keyword:`!break` を実行せずに" "ループが終了すると、:keyword:`!else` 節が実行されます。" #: ../../tutorial/controlflow.rst:208 msgid "" "In a :keyword:`for` loop, the :keyword:`!else` clause is executed after the " "loop finishes its final iteration, that is, if no break occurred." msgstr "" ":keyword:`for` 文の場合、 :keyword:`!else` 節はループ処理の最後のイテレーショ" "ンが実行されたあと、つまりbreakが発生しなかった場合に実行されます。" #: ../../tutorial/controlflow.rst:211 msgid "" "In a :keyword:`while` loop, it's executed after the loop's condition becomes " "false." msgstr "" ":keyword:`while` 文の場合は、ループ条件が偽となったあとに実行されます。" #: ../../tutorial/controlflow.rst:213 msgid "" "In either kind of loop, the :keyword:`!else` clause is **not** executed if " "the loop was terminated by a :keyword:`break`. Of course, other ways of " "ending the loop early, such as a :keyword:`return` or a raised exception, " "will also skip execution of the :keyword:`else` clause." msgstr "" "どちらのループでも、ループが :keyword:`break` によって終了した場合は :" "keyword:`!else` 句は **実行されません**。当然、 :keyword:`return` や例外の発" "生によってループが途中で終了した場合にも、:keyword:`else` 節の実行はスキップ" "されます。" #: ../../tutorial/controlflow.rst:218 msgid "" "This is exemplified in the following :keyword:`!for` loop, which searches " "for prime numbers::" msgstr "その例として、素数を探索する :keyword:`!for` 文を以下に示します::" #: ../../tutorial/controlflow.rst:221 msgid "" ">>> for n in range(2, 10):\n" "... for x in range(2, n):\n" "... if n % x == 0:\n" "... print(n, 'equals', x, '*', n//x)\n" "... break\n" "... else:\n" "... # loop fell through without finding a factor\n" "... print(n, 'is a prime number')\n" "...\n" "2 is a prime number\n" "3 is a prime number\n" "4 equals 2 * 2\n" "5 is a prime number\n" "6 equals 2 * 3\n" "7 is a prime number\n" "8 equals 2 * 4\n" "9 equals 3 * 3" msgstr "" ">>> for n in range(2, 10):\n" "... for x in range(2, n):\n" "... if n % x == 0:\n" "... print(n, 'は', x, '*', n//x, 'と等しい')\n" "... break\n" "... else:\n" "... # 因数が見つからないとループは最後まで実行される\n" "... print(n, 'は素数です')\n" "...\n" "2 is a prime number\n" "3 is a prime number\n" "4 equals 2 * 2\n" "5 is a prime number\n" "6 equals 2 * 3\n" "7 is a prime number\n" "8 equals 2 * 4\n" "9 equals 3 * 3" #: ../../tutorial/controlflow.rst:239 msgid "" "(Yes, this is the correct code. Look closely: the ``else`` clause belongs " "to the ``for`` loop, **not** the ``if`` statement.)" msgstr "" "(そう、これは正しいコードです。よく見てください: ``else`` 節は ``if`` 文 **で" "はなく** 、 ``for`` ループに属しています。)" #: ../../tutorial/controlflow.rst:242 msgid "" "One way to think of the else clause is to imagine it paired with the ``if`` " "inside the loop. As the loop executes, it will run a sequence like if/if/if/" "else. The ``if`` is inside the loop, encountered a number of times. If the " "condition is ever true, a ``break`` will happen. If the condition is never " "true, the ``else`` clause outside the loop will execute." msgstr "" #: ../../tutorial/controlflow.rst:248 msgid "" "When used with a loop, the ``else`` clause has more in common with the " "``else`` clause of a :keyword:`try` statement than it does with that of " "``if`` statements: a ``try`` statement's ``else`` clause runs when no " "exception occurs, and a loop's ``else`` clause runs when no ``break`` " "occurs. For more on the ``try`` statement and exceptions, see :ref:`tut-" "handling`." msgstr "" "ループの ``else`` 句は、 ``if`` 文の ``else`` よりも :keyword:`try` 文の " "``else`` に似ています。 文の ``else`` 句は例外が発生しなかった時に実行され、" "ループの ``else`` 句は ``break`` されなかった場合に実行されます。 ``try`` 文" "と例外についての詳細は :ref:`tut-handling` を参照してください。" #: ../../tutorial/controlflow.rst:258 msgid ":keyword:`!pass` Statements" msgstr ":keyword:`!pass` 文" #: ../../tutorial/controlflow.rst:260 msgid "" "The :keyword:`pass` statement does nothing. It can be used when a statement " "is required syntactically but the program requires no action. For example::" msgstr "" ":keyword:`pass` 文は何もしません。 :keyword:`pass` は、文を書くことが構文上要" "求されているが、プログラム上何の動作もする必要がない時に使われます::" #: ../../tutorial/controlflow.rst:263 msgid "" ">>> while True:\n" "... pass # Busy-wait for keyboard interrupt (Ctrl+C)\n" "..." msgstr "" ">>> while True:\n" "... pass # キーボード割り込み(Ctrl+C)のためのビジーウェイト\n" "..." #: ../../tutorial/controlflow.rst:267 msgid "This is commonly used for creating minimal classes::" msgstr "これは最小のクラスを作るときによく使われる方法です::" #: ../../tutorial/controlflow.rst:269 msgid "" ">>> class MyEmptyClass:\n" "... pass\n" "..." msgstr "" ">>> class MyEmptyClass:\n" "... pass\n" "..." #: ../../tutorial/controlflow.rst:273 msgid "" "Another place :keyword:`pass` can be used is as a place-holder for a " "function or conditional body when you are working on new code, allowing you " "to keep thinking at a more abstract level. The :keyword:`!pass` is silently " "ignored::" msgstr "" ":keyword:`pass` のもう 1 つの使い道は、新しいコードを書いているときの関数や条" "件文の仮置きの本体としてです。こうすることで、より抽象的なレベルで考え続けら" "れます。\n" ":keyword:`!pass` は何事も無く無視されます ::" #: ../../tutorial/controlflow.rst:277 msgid "" ">>> def initlog(*args):\n" "... pass # Remember to implement this!\n" "..." msgstr "" ">>> def initlog(*args):\n" "... pass # ここを忘れずに実装すること!\n" "..." #: ../../tutorial/controlflow.rst:281 msgid "" "For this last case, many people use the ellipsis literal :code:`...` instead " "of :code:`pass`. This use has no special meaning to Python, and is not part " "of the language definition (you could use any constant expression here), " "but :code:`...` is used conventionally as a placeholder body as well. See :" "ref:`bltin-ellipsis-object`." msgstr "" "この最後の例で、多くの人は :code:`pass` ではなく省略記号リテラル :code:`...` " "を使います。 この使い方は Python に対して特別な意味はなく、言語定義の一部でも" "ありません(ここにはどんな定数式でも使えます)が、 :code:`...` は慣例的にプ" "レースホルダ本体としても使われています。 :ref:`bltin-ellipsis-object` を参照" "してください。" #: ../../tutorial/controlflow.rst:291 msgid ":keyword:`!match` Statements" msgstr ":keyword:`!match` 文" #: ../../tutorial/controlflow.rst:293 msgid "" "A :keyword:`match` statement takes an expression and compares its value to " "successive patterns given as one or more case blocks. This is superficially " "similar to a switch statement in C, Java or JavaScript (and many other " "languages), but it's more similar to pattern matching in languages like Rust " "or Haskell. Only the first pattern that matches gets executed and it can " "also extract components (sequence elements or object attributes) from the " "value into variables. If no case matches, none of the branches is executed." msgstr "" ":keyword:`match` 文は1つの式を指定し、その値と次に続く1つ以上のcaseブロックに" "指定されたパターンを比較します。この機能はCやJava、JavaScript(や他の多数の言" "語)のswitch文と表面的には似ていますが、RustやHaskellのパターンマッチングによ" "り似ています。最初にマッチしたパターンのみが実行され、コンポーネント(シーケン" "スの要素やオブジェクトの属性)から値を取り出して変数に代入することもできます。" "どのcaseにもマッチしない場合はどの分岐も実行されません。" #: ../../tutorial/controlflow.rst:302 msgid "" "The simplest form compares a subject value against one or more literals::" msgstr "最も単純な形式は、対象の値に対して1つ以上のリテラルです::" #: ../../tutorial/controlflow.rst:304 msgid "" "def http_error(status):\n" " match status:\n" " case 400:\n" " return \"Bad request\"\n" " case 404:\n" " return \"Not found\"\n" " case 418:\n" " return \"I'm a teapot\"\n" " case _:\n" " return \"Something's wrong with the internet\"" msgstr "" "def http_error(status):\n" " match status:\n" " case 400:\n" " return \"Bad request\"\n" " case 404:\n" " return \"Not found\"\n" " case 418:\n" " return \"I'm a teapot\"\n" " case _:\n" " return \"Something's wrong with the internet\"" #: ../../tutorial/controlflow.rst:315 msgid "" "Note the last block: the \"variable name\" ``_`` acts as a *wildcard* and " "never fails to match." msgstr "" "最後のブロックについて: 変数名 ``_`` は *ワイルドカード* の働きをし、マッチに" "絶対失敗しません。" #: ../../tutorial/controlflow.rst:318 msgid "" "You can combine several literals in a single pattern using ``|`` (\"or\")::" msgstr "" "複数のリテラルを ``|`` (\"or\")を使用して組み合わせて1つのパターンにできま" "す::" #: ../../tutorial/controlflow.rst:320 msgid "" "case 401 | 403 | 404:\n" " return \"Not allowed\"" msgstr "" "case 401 | 403 | 404:\n" " return \"Not allowed\"" #: ../../tutorial/controlflow.rst:323 msgid "" "Patterns can look like unpacking assignments, and can be used to bind " "variables::" msgstr "パターンはアンパック代入ができ、変数に結びつけられます::" #: ../../tutorial/controlflow.rst:326 msgid "" "# point is an (x, y) tuple\n" "match point:\n" " case (0, 0):\n" " print(\"Origin\")\n" " case (0, y):\n" " print(f\"Y={y}\")\n" " case (x, 0):\n" " print(f\"X={x}\")\n" " case (x, y):\n" " print(f\"X={x}, Y={y}\")\n" " case _:\n" " raise ValueError(\"Not a point\")" msgstr "" "# point(座標) は (x, y) のタプル\n" "match point:\n" " case (0, 0):\n" " print(\"原点\")\n" " case (0, y):\n" " print(f\"Y={y}\")\n" " case (x, 0):\n" " print(f\"X={x}\")\n" " case (x, y):\n" " print(f\"X={x}, Y={y}\")\n" " case _:\n" " raise ValueError(\"座標ではない\")" #: ../../tutorial/controlflow.rst:339 msgid "" "Study that one carefully! The first pattern has two literals, and can be " "thought of as an extension of the literal pattern shown above. But the next " "two patterns combine a literal and a variable, and the variable *binds* a " "value from the subject (``point``). The fourth pattern captures two values, " "which makes it conceptually similar to the unpacking assignment ``(x, y) = " "point``." msgstr "" "このコードは注意して見てください!\n" "最初のパターンには2つのリテラルがあり、上で示したリテラルパターンの拡張と考え" "ることができます。\n" "しかし次の2つのパターンはリテラルと変数の組み合わせのため、対象(``point``)か" "ら値を取り出して変数に *結びつけ* ます。\n" "4番目のパターンは2つの値を取り込みます。\n" "これは、アンパック代入 ``(x, y) = point`` と概念的に似ています。" #: ../../tutorial/controlflow.rst:346 msgid "" "If you are using classes to structure your data you can use the class name " "followed by an argument list resembling a constructor, but with the ability " "to capture attributes into variables::" msgstr "" "データを構造化するためにクラスを使っている場合は、クラス名の後ろにコンストラ" "クターのように引数のリストを指定できます。属性の値は変数に取り込まれます。" #: ../../tutorial/controlflow.rst:350 msgid "" "class Point:\n" " def __init__(self, x, y):\n" " self.x = x\n" " self.y = y\n" "\n" "def where_is(point):\n" " match point:\n" " case Point(x=0, y=0):\n" " print(\"Origin\")\n" " case Point(x=0, y=y):\n" " print(f\"Y={y}\")\n" " case Point(x=x, y=0):\n" " print(f\"X={x}\")\n" " case Point():\n" " print(\"Somewhere else\")\n" " case _:\n" " print(\"Not a point\")" msgstr "" "class Point:\n" " def __init__(self, x, y):\n" " self.x = x\n" " self.y = y\n" "\n" "def where_is(point):\n" " match point:\n" " case Point(x=0, y=0):\n" " print(\"原点\")\n" " case Point(x=0, y=y):\n" " print(f\"Y={y}\")\n" " case Point(x=x, y=0):\n" " print(f\"X={x}\")\n" " case Point():\n" " print(\"それ以外のどこか\")\n" " case _:\n" " print(\"座標ではない\")" #: ../../tutorial/controlflow.rst:368 msgid "" "You can use positional parameters with some builtin classes that provide an " "ordering for their attributes (e.g. dataclasses). You can also define a " "specific position for attributes in patterns by setting the " "``__match_args__`` special attribute in your classes. If it's set to (\"x\", " "\"y\"), the following patterns are all equivalent (and all bind the ``y`` " "attribute to the ``var`` variable)::" msgstr "" "いくつかの組み込みクラスでは位置引数が使用でき、属性の順番を提供します(例: " "データクラス)。クラスの ``__match_args__`` 特殊属性によって、パターンの中で属" "性の明確な位置を定義することもできます。(\"x\", \"y\")が設定された場合、以下" "のすべてのパターンは等価です(すべて属性 ``y`` が ``var`` 変数に結びつけられま" "す)::" #: ../../tutorial/controlflow.rst:374 msgid "" "Point(1, var)\n" "Point(1, y=var)\n" "Point(x=1, y=var)\n" "Point(y=var, x=1)" msgstr "" "Point(1, var)\n" "Point(1, y=var)\n" "Point(x=1, y=var)\n" "Point(y=var, x=1)" #: ../../tutorial/controlflow.rst:379 msgid "" "A recommended way to read patterns is to look at them as an extended form of " "what you would put on the left of an assignment, to understand which " "variables would be set to what. Only the standalone names (like ``var`` " "above) are assigned to by a match statement. Dotted names (like ``foo." "bar``), attribute names (the ``x=`` and ``y=`` above) or class names " "(recognized by the \"(...)\" next to them like ``Point`` above) are never " "assigned to." msgstr "" "おすすめのパターンの読み方は、パターンが、代入文の左辺に配置するものを拡張し" "た形式であるとみなすことです。\n" "これにより、どの変数になにが代入されるかが分かります。\n" "単独の名前(上記の ``var`` など)だけがマッチ文で値が代入されます。ドット付き" "の名前(``foo.bar`` など)、属性名(上記の ``x=``、``y=`` など )、クラス名" "(名前の後ろの \"(...)\" によって判別される。上記の ``Point`` など)には値は" "代入されません。" #: ../../tutorial/controlflow.rst:386 msgid "" "Patterns can be arbitrarily nested. For example, if we have a short list of " "Points, with ``__match_args__`` added, we could match it like this::" msgstr "" "パターンはいくらでも入れ子 (ネスト) にすることができます。例えば、 " "``__match_args__`` を追加した Point クラスのリストに対して次のようにマッチを" "行うことができます::" #: ../../tutorial/controlflow.rst:389 msgid "" "class Point:\n" " __match_args__ = ('x', 'y')\n" " def __init__(self, x, y):\n" " self.x = x\n" " self.y = y\n" "\n" "match points:\n" " case []:\n" " print(\"No points\")\n" " case [Point(0, 0)]:\n" " print(\"The origin\")\n" " case [Point(x, y)]:\n" " print(f\"Single point {x}, {y}\")\n" " case [Point(0, y1), Point(0, y2)]:\n" " print(f\"Two on the Y axis at {y1}, {y2}\")\n" " case _:\n" " print(\"Something else\")" msgstr "" "class Point:\n" " __match_args__ = ('x', 'y')\n" " def __init__(self, x, y):\n" " self.x = x\n" " self.y = y\n" "\n" "match points:\n" " case []:\n" " print(\"座標が存在しない\")\n" " case [Point(0, 0)]:\n" " print(\"原点\")\n" " case [Point(x, y)]:\n" " print(f\"1つの座標 {x}, {y}\")\n" " case [Point(0, y1), Point(0, y2)]:\n" " print(f\"Y軸の {y1}, {y2} に2つの座標\")\n" " case _:\n" " print(\"それ以外のどこか\")" #: ../../tutorial/controlflow.rst:407 msgid "" "We can add an ``if`` clause to a pattern, known as a \"guard\". If the " "guard is false, ``match`` goes on to try the next case block. Note that " "value capture happens before the guard is evaluated::" msgstr "" "パターンに ``if`` 節を追加できます。これは \"ガード\" と呼ばれます。ガードが" "falseの場合、``match`` は次のcaseブロックの処理に移動します。ガードを評価する" "前に値が取り込まれることに注意してください::" #: ../../tutorial/controlflow.rst:411 msgid "" "match point:\n" " case Point(x, y) if x == y:\n" " print(f\"Y=X at {x}\")\n" " case Point(x, y):\n" " print(f\"Not on the diagonal\")" msgstr "" "match point:\n" " case Point(x, y) if x == y:\n" " print(f\"Y=X at {x}\")\n" " case Point(x, y):\n" " print(f\"対角線上ではない\")" #: ../../tutorial/controlflow.rst:417 msgid "Several other key features of this statement:" msgstr "この文のその他のいくつか重要な特徴::" #: ../../tutorial/controlflow.rst:419 msgid "" "Like unpacking assignments, tuple and list patterns have exactly the same " "meaning and actually match arbitrary sequences. An important exception is " "that they don't match iterators or strings." msgstr "" "アンパック代入のように、タプルとリストのパターンでは正確に同じ意味で、任意の" "シーケンスと一致します。重要な例外として、イテレーターや文字列ではマッチしま" "せん。" #: ../../tutorial/controlflow.rst:423 msgid "" "Sequence patterns support extended unpacking: ``[x, y, *rest]`` and ``(x, y, " "*rest)`` work similar to unpacking assignments. The name after ``*`` may " "also be ``_``, so ``(x, y, *_)`` matches a sequence of at least two items " "without binding the remaining items." msgstr "" "シーケンスパターンは拡張アンパックをサポート: ``[x, y, *rest]`` と ``(x, y, " "*rest)`` はアンパック代入として同じように動作します。``*`` のあとの変数名は " "``_`` でもよく、そのため ``(x, y, *_)`` は最低でも2つのアイテムを持つシーケン" "スにマッチし、残りのアイテムは変数に結びつけられません。" #: ../../tutorial/controlflow.rst:428 msgid "" "Mapping patterns: ``{\"bandwidth\": b, \"latency\": l}`` captures the " "``\"bandwidth\"`` and ``\"latency\"`` values from a dictionary. Unlike " "sequence patterns, extra keys are ignored. An unpacking like ``**rest`` is " "also supported. (But ``**_`` would be redundant, so it is not allowed.)" msgstr "" "マッピングパターン: ``{\"bandwidth\": b, \"latency\": l}`` は辞書から " "``\"bandwidth\"`` と ``\"latency\"`` の値を取り込みます。シーケンスパターンと" "は異なり、それ以外のキーは無視されます。アンパッキングのような ``**rest`` も" "サポートされています(しかし、 ``**_`` は冗長なため禁止されています)。" #: ../../tutorial/controlflow.rst:433 msgid "Subpatterns may be captured using the ``as`` keyword::" msgstr "サブパターンでは ``as`` キーワードを使用して値を取り込みます::" #: ../../tutorial/controlflow.rst:435 msgid "case (Point(x1, y1), Point(x2, y2) as p2): ..." msgstr "case (Point(x1, y1), Point(x2, y2) as p2): ..." #: ../../tutorial/controlflow.rst:437 msgid "" "will capture the second element of the input as ``p2`` (as long as the input " "is a sequence of two points)" msgstr "" "この例では入力から2番目の要素を ``p2`` として取り込みます(入力が2つのポイン" "トのシーケンスである場合)" #: ../../tutorial/controlflow.rst:440 msgid "" "Most literals are compared by equality, however the singletons ``True``, " "``False`` and ``None`` are compared by identity." msgstr "" "ほとんどのリテラルは同一性を比較しますが、シングルトンの ``True``、" "``False``、``None`` では識別値を比較します。" #: ../../tutorial/controlflow.rst:443 msgid "" "Patterns may use named constants. These must be dotted names to prevent " "them from being interpreted as capture variables::" msgstr "" #: ../../tutorial/controlflow.rst:446 msgid "" "from enum import Enum\n" "class Color(Enum):\n" " RED = 'red'\n" " GREEN = 'green'\n" " BLUE = 'blue'\n" "\n" "color = Color(input(\"Enter your choice of 'red', 'blue' or 'green': \"))\n" "\n" "match color:\n" " case Color.RED:\n" " print(\"I see red!\")\n" " case Color.GREEN:\n" " print(\"Grass is green\")\n" " case Color.BLUE:\n" " print(\"I'm feeling the blues :(\")" msgstr "" "from enum import Enum\n" "class Color(Enum):\n" " RED = 'red'\n" " GREEN = 'green'\n" " BLUE = 'blue'\n" "\n" "color = Color(input(\"Enter your choice of 'red', 'blue' or 'green': \"))\n" "\n" "match color:\n" " case Color.RED:\n" " print(\"I see red!\")\n" " case Color.GREEN:\n" " print(\"Grass is green\")\n" " case Color.BLUE:\n" " print(\"I'm feeling the blues :(\")" #: ../../tutorial/controlflow.rst:462 msgid "" "For a more detailed explanation and additional examples, you can look into :" "pep:`636` which is written in a tutorial format." msgstr "" "より詳細な説明と追加の例は :pep:`636` にチュートリアル形式で記述してありま" "す。" #: ../../tutorial/controlflow.rst:468 msgid "Defining Functions" msgstr "関数を定義する" #: ../../tutorial/controlflow.rst:470 msgid "" "We can create a function that writes the Fibonacci series to an arbitrary " "boundary::" msgstr "" "フィボナッチ数列 (Fibonacci series) を任意の上限値まで書き出すような関数を作" "成できます::" #: ../../tutorial/controlflow.rst:473 msgid "" ">>> def fib(n): # write Fibonacci series less than n\n" "... \"\"\"Print a Fibonacci series less than n.\"\"\"\n" "... a, b = 0, 1\n" "... while a < n:\n" "... print(a, end=' ')\n" "... a, b = b, a+b\n" "... print()\n" "...\n" ">>> # Now call the function we just defined:\n" ">>> fib(2000)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597" msgstr "" ">>> def fib(n): # nまでのフィボナッチ数を出力する\n" "... \"\"\"nまでのフィボナッチ数をprintする。\"\"\"\n" "... a, b = 0, 1\n" "... while a < n:\n" "... print(a, end=' ')\n" "... a, b = b, a+b\n" "... print()\n" "...\n" ">>> # 定義した関数を呼び出す:\n" ">>> fib(2000)\n" "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597" #: ../../tutorial/controlflow.rst:490 msgid "" "The keyword :keyword:`def` introduces a function *definition*. It must be " "followed by the function name and the parenthesized list of formal " "parameters. The statements that form the body of the function start at the " "next line, and must be indented." msgstr "" ":keyword:`def` は関数の *定義 (definition)* を導くキーワードです。 :keyword:" "`def` の後には、関数名と仮引数を丸括弧で囲んだリストを続けなければなりませ" "ん。関数の実体を構成する実行文は次の行から始め、インデントされていなければな" "りません。" #: ../../tutorial/controlflow.rst:495 msgid "" "The first statement of the function body can optionally be a string literal; " "this string literal is the function's documentation string, or :dfn:" "`docstring`. (More about docstrings can be found in the section :ref:`tut-" "docstrings`.) There are tools which use docstrings to automatically produce " "online or printed documentation, or to let the user interactively browse " "through code; it's good practice to include docstrings in code that you " "write, so make a habit of it." msgstr "" "関数の本体の記述する文の最初の行は文字列リテラルにすることもできます。その場" "合、この文字列は関数のドキュメンテーション文字列 (documentation string)、また" "は :dfn:`docstring` と呼ばれます。 (docstring については :ref:`tut-" "docstrings` でさらに扱っています。) ドキュメンテーション文字列を使ったツール" "には、オンライン文書や印刷文書を自動的に生成したり、ユーザが対話的にコードか" "ら直接閲覧できるようにするものがあります。自分が書くコードにドキュメンテー" "ション文字列を入れるのはよい習慣です。書く癖をつけてください。" #: ../../tutorial/controlflow.rst:502 msgid "" "The *execution* of a function introduces a new symbol table used for the " "local variables of the function. More precisely, all variable assignments " "in a function store the value in the local symbol table; whereas variable " "references first look in the local symbol table, then in the local symbol " "tables of enclosing functions, then in the global symbol table, and finally " "in the table of built-in names. Thus, global variables and variables of " "enclosing functions cannot be directly assigned a value within a function " "(unless, for global variables, named in a :keyword:`global` statement, or, " "for variables of enclosing functions, named in a :keyword:`nonlocal` " "statement), although they may be referenced." msgstr "" "関数を *実行 (execution)* するとき、関数のローカル変数のために使われる新たな" "シンボルテーブル (symbol table) が用意されます。\n" "もっと正確にいうと、関数内で変数への代入を行うと、その値はすべてこのローカル" "なシンボルテーブルに記憶されます。\n" "一方、変数の参照を行うと、まずローカルなシンボルテーブルが検索され、次にさら" "に外側の関数のローカルなシンボルテーブルを検索し、その後グローバルなシンボル" "テーブルを調べ、最後に組み込みの名前テーブルを調べます。\n" "従って、関数の中では (グローバル変数が :keyword:`global` 文で指定されていた" "り、外側の関数の変数が :keyword:`nonlocal` 文で指定されていない限り) グローバ" "ル変数や外側の関数の変数に直接値を代入できませんが、参照することはできます。" #: ../../tutorial/controlflow.rst:513 msgid "" "The actual parameters (arguments) to a function call are introduced in the " "local symbol table of the called function when it is called; thus, arguments " "are passed using *call by value* (where the *value* is always an object " "*reference*, not the value of the object). [#]_ When a function calls " "another function, or calls itself recursively, a new local symbol table is " "created for that call." msgstr "" "関数を呼び出す際の実際の引数 (実引数) は、関数が呼び出されるときに関数のロー" "カルなシンボルテーブル内に取り込まれます。そうすることで、実引数は *値渡し " "(call by value)* で関数に渡されることになります (ここでの *値 (value)* とは常" "にオブジェクトへの *参照(reference)* をいい、オブジェクトの値そのものではあり" "ません) [#]_。ある関数がほかの関数を呼び出すときや、自身を再帰的に呼び出すと" "きには、新たな呼び出しのためにローカルなシンボルテーブルが新たに作成されま" "す。" #: ../../tutorial/controlflow.rst:520 msgid "" "A function definition associates the function name with the function object " "in the current symbol table. The interpreter recognizes the object pointed " "to by that name as a user-defined function. Other names can also point to " "that same function object and can also be used to access the function::" msgstr "" "関数の定義を行うと、関数名は関数オブジェクトとともに現在のシンボルテーブル内" "に取り入れられます。インタープリタはその名前が指すオブジェクトをユーザ定義関" "数 (user-defined function) として認識します。他の名前も同じ関数オブジェクトを" "指すことができ、またその関数にアクセスするために使用することができます::" #: ../../tutorial/controlflow.rst:525 msgid "" ">>> fib\n" "\n" ">>> f = fib\n" ">>> f(100)\n" "0 1 1 2 3 5 8 13 21 34 55 89" msgstr "" ">>> fib\n" "\n" ">>> f = fib\n" ">>> f(100)\n" "0 1 1 2 3 5 8 13 21 34 55 89" #: ../../tutorial/controlflow.rst:531 msgid "" "Coming from other languages, you might object that ``fib`` is not a function " "but a procedure since it doesn't return a value. In fact, even functions " "without a :keyword:`return` statement do return a value, albeit a rather " "boring one. This value is called ``None`` (it's a built-in name). Writing " "the value ``None`` is normally suppressed by the interpreter if it would be " "the only value written. You can see it if you really want to using :func:" "`print`::" msgstr "" "他の言語出身の人からは、 ``fib`` は値を返さないので関数ではなく手続き " "(procedure) だと異論があるかもしれませんね。技術的に言えば、実際には :" "keyword:`return` 文を持たない関数もややつまらない値ですが値を返しています。こ" "の値は ``None`` と呼ばれます (これは組み込みの名前です)。 ``None`` だけを書き" "出そうとすると、インタプリタは通常出力を抑制します。本当に出力したいのなら、" "以下のように :func:`print` を使うと見ることができます::" #: ../../tutorial/controlflow.rst:538 msgid "" ">>> fib(0)\n" ">>> print(fib(0))\n" "None" msgstr "" ">>> fib(0)\n" ">>> print(fib(0))\n" "None" #: ../../tutorial/controlflow.rst:542 msgid "" "It is simple to write a function that returns a list of the numbers of the " "Fibonacci series, instead of printing it::" msgstr "" "フィボナッチ数列の数からなるリストを出力する代わりに、値を返すような関数を書" "くのは簡単です::" #: ../../tutorial/controlflow.rst:545 msgid "" ">>> def fib2(n): # return Fibonacci series up to n\n" "... \"\"\"Return a list containing the Fibonacci series up to n.\"\"\"\n" "... result = []\n" "... a, b = 0, 1\n" "... while a < n:\n" "... result.append(a) # see below\n" "... a, b = b, a+b\n" "... return result\n" "...\n" ">>> f100 = fib2(100) # call it\n" ">>> f100 # write the result\n" "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]" msgstr "" ">>> def fib2(n): # nまでのフィボナッチ数を返す\n" "... \"\"\"nまでのフィボナッチ数を含むリストを返す。\"\"\"\n" "... result = []\n" "... a, b = 0, 1\n" "... while a < n:\n" "... result.append(a) # 以下参照\n" "... a, b = b, a+b\n" "... return result\n" "...\n" ">>> f100 = fib2(100) # 関数を呼び出す\n" ">>> f100 # 結果を出力する\n" "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]" #: ../../tutorial/controlflow.rst:558 msgid "This example, as usual, demonstrates some new Python features:" msgstr "この例は Python の新しい機能を示しています:" #: ../../tutorial/controlflow.rst:560 msgid "" "The :keyword:`return` statement returns with a value from a function. :" "keyword:`!return` without an expression argument returns ``None``. Falling " "off the end of a function also returns ``None``." msgstr "" ":keyword:`return` 文では、関数から一つ値を返します。 :keyword:`!return` の引" "数となる式がない場合、 ``None`` が返ります。関数が終了したときにも ``None`` " "が返ります。" #: ../../tutorial/controlflow.rst:564 msgid "" "The statement ``result.append(a)`` calls a *method* of the list object " "``result``. A method is a function that 'belongs' to an object and is named " "``obj.methodname``, where ``obj`` is some object (this may be an " "expression), and ``methodname`` is the name of a method that is defined by " "the object's type. Different types define different methods. Methods of " "different types may have the same name without causing ambiguity. (It is " "possible to define your own object types and methods, using *classes*, see :" "ref:`tut-classes`) The method :meth:`~list.append` shown in the example is " "defined for list objects; it adds a new element at the end of the list. In " "this example it is equivalent to ``result = result + [a]``, but more " "efficient." msgstr "" "文 ``result.append(a)`` では、リストオブジェクト ``result`` の *メソッド " "(method)* を呼び出しています。メソッドとは、オブジェクトに '属している' 関数" "のことで、 ``obj`` を何らかのオブジェクト (式であっても構いません)、 " "``methodname`` をそのオブジェクトで定義されているメソッド名とすると、 ``obj." "methodname`` と書き表されます。異なる型は異なるメソッドを定義しています。異な" "る型のメソッドで同じ名前のメソッドを持つことができ、あいまいさを生じることは" "ありません。 (*クラス (class)* を使うことで、自前のオブジェクト型とメソッドを" "定義することもできます。 :ref:`tut-classes` 参照) 例で示されているメソッド :" "meth:`append` は、リストオブジェクトで定義されています; このメソッドはリスト" "の末尾に新たな要素を追加します。この例での :meth:`~list.append` は ``result " "= result + [a]`` と等価ですが、より効率的です。" #: ../../tutorial/controlflow.rst:579 msgid "More on Defining Functions" msgstr "関数定義についてもう少し" #: ../../tutorial/controlflow.rst:581 msgid "" "It is also possible to define functions with a variable number of arguments. " "There are three forms, which can be combined." msgstr "" "可変個の引数を伴う関数を定義することもできます。引数の定義方法には 3 つの形式" "があり、それらを組み合わせることができます。" #: ../../tutorial/controlflow.rst:588 msgid "Default Argument Values" msgstr "デフォルトの引数値" #: ../../tutorial/controlflow.rst:590 msgid "" "The most useful form is to specify a default value for one or more " "arguments. This creates a function that can be called with fewer arguments " "than it is defined to allow. For example::" msgstr "" "もっとも便利なのは、一つ以上の引数に対してデフォルトの値を指定する形式です。" "この形式を使うと、定義されている引数より少ない個数の引数で呼び出せる関数を作" "成します::" #: ../../tutorial/controlflow.rst:594 msgid "" "def ask_ok(prompt, retries=4, reminder='Please try again!'):\n" " while True:\n" " reply = input(prompt)\n" " if reply in {'y', 'ye', 'yes'}:\n" " return True\n" " if reply in {'n', 'no', 'nop', 'nope'}:\n" " return False\n" " retries = retries - 1\n" " if retries < 0:\n" " raise ValueError('invalid user response')\n" " print(reminder)" msgstr "" "def ask_ok(prompt, retries=4, reminder='再試行してください!'):\n" " while True:\n" " reply = input(prompt)\n" " if reply in {'y', 'ye', 'yes'}:\n" " return True\n" " if reply in {'n', 'no', 'nop', 'nope'}:\n" " return False\n" " retries = retries - 1\n" " if retries < 0:\n" " raise ValueError('無効なユーザーの入力')\n" " print(reminder)" #: ../../tutorial/controlflow.rst:606 msgid "This function can be called in several ways:" msgstr "この関数はいくつかの方法で呼び出せます:" #: ../../tutorial/controlflow.rst:608 msgid "" "giving only the mandatory argument: ``ask_ok('Do you really want to quit?')``" msgstr "必須の引数のみ与える: ``ask_ok('Do you really want to quit?')``" #: ../../tutorial/controlflow.rst:610 msgid "" "giving one of the optional arguments: ``ask_ok('OK to overwrite the file?', " "2)``" msgstr "" "一つのオプション引数を与える: ``ask_ok('OK to overwrite the file?', 2)``" #: ../../tutorial/controlflow.rst:612 msgid "" "or even giving all arguments: ``ask_ok('OK to overwrite the file?', 2, 'Come " "on, only yes or no!')``" msgstr "" "全ての引数を与える: ``ask_ok('OK to overwrite the file?', 2, 'Come on, only " "yes or no!')``" #: ../../tutorial/controlflow.rst:615 msgid "" "This example also introduces the :keyword:`in` keyword. This tests whether " "or not a sequence contains a certain value." msgstr "" "この例では :keyword:`in` キーワードが導入されています。このキーワードはシーケ" "ンスが特定の値を含んでいるかどうか調べるのに使われます。" #: ../../tutorial/controlflow.rst:618 msgid "" "The default values are evaluated at the point of function definition in the " "*defining* scope, so that ::" msgstr "" "デフォルト値は、関数が定義された時点で、関数を *定義している* 側のスコープ " "(scope) で評価されるので ::" #: ../../tutorial/controlflow.rst:621 msgid "" "i = 5\n" "\n" "def f(arg=i):\n" " print(arg)\n" "\n" "i = 6\n" "f()" msgstr "" "i = 5\n" "\n" "def f(arg=i):\n" " print(arg)\n" "\n" "i = 6\n" "f()" #: ../../tutorial/controlflow.rst:629 msgid "will print ``5``." msgstr "は ``5`` を出力します。" #: ../../tutorial/controlflow.rst:631 msgid "" "**Important warning:** The default value is evaluated only once. This makes " "a difference when the default is a mutable object such as a list, " "dictionary, or instances of most classes. For example, the following " "function accumulates the arguments passed to it on subsequent calls::" msgstr "" "**重要な警告:** デフォルト値は 1 度だけしか評価されません。デフォルト値がリ" "ストや辞書のような変更可能なオブジェクトの時にはその影響がでます。例えば以下" "の関数は、後に続く関数呼び出しで関数に渡されている引数を累積します::" #: ../../tutorial/controlflow.rst:636 msgid "" "def f(a, L=[]):\n" " L.append(a)\n" " return L\n" "\n" "print(f(1))\n" "print(f(2))\n" "print(f(3))" msgstr "" "def f(a, L=[]):\n" " L.append(a)\n" " return L\n" "\n" "print(f(1))\n" "print(f(2))\n" "print(f(3))" #: ../../tutorial/controlflow.rst:644 msgid "This will print ::" msgstr "このコードは、以下を出力します ::" #: ../../tutorial/controlflow.rst:646 msgid "" "[1]\n" "[1, 2]\n" "[1, 2, 3]" msgstr "" "[1]\n" "[1, 2]\n" "[1, 2, 3]" #: ../../tutorial/controlflow.rst:650 msgid "" "If you don't want the default to be shared between subsequent calls, you can " "write the function like this instead::" msgstr "" "後続の関数呼び出しでデフォルト値を共有したくなければ、代わりに以下のように関" "数を書くことができます::" #: ../../tutorial/controlflow.rst:653 msgid "" "def f(a, L=None):\n" " if L is None:\n" " L = []\n" " L.append(a)\n" " return L" msgstr "" "def f(a, L=None):\n" " if L is None:\n" " L = []\n" " L.append(a)\n" " return L" #: ../../tutorial/controlflow.rst:663 msgid "Keyword Arguments" msgstr "キーワード引数" #: ../../tutorial/controlflow.rst:665 msgid "" "Functions can also be called using :term:`keyword arguments ` of the form ``kwarg=value``. For instance, the following " "function::" msgstr "" "関数を ``kwarg=value`` という形式の :term:`キーワード引数 ` を使って呼び出すこともできます。例えば、以下の関数::" #: ../../tutorial/controlflow.rst:668 msgid "" "def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):\n" " print(\"-- This parrot wouldn't\", action, end=' ')\n" " print(\"if you put\", voltage, \"volts through it.\")\n" " print(\"-- Lovely plumage, the\", type)\n" " print(\"-- It's\", state, \"!\")" msgstr "" "def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):\n" " print(\"-- This parrot wouldn't\", action, end=' ')\n" " print(\"if you put\", voltage, \"volts through it.\")\n" " print(\"-- Lovely plumage, the\", type)\n" " print(\"-- It's\", state, \"!\")" #: ../../tutorial/controlflow.rst:674 msgid "" "accepts one required argument (``voltage``) and three optional arguments " "(``state``, ``action``, and ``type``). This function can be called in any " "of the following ways::" msgstr "" "は、必須引数 (``voltage``) とオプション引数 (``state``、``action``、" "``type``) を受け付けます。この関数は以下のいずれかの方法で呼び出せます::" #: ../../tutorial/controlflow.rst:678 msgid "" "parrot(1000) # 1 positional " "argument\n" "parrot(voltage=1000) # 1 keyword argument\n" "parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments\n" "parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments\n" "parrot('a million', 'bereft of life', 'jump') # 3 positional " "arguments\n" "parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 " "keyword" msgstr "" "parrot(1000) # 1つの位置引数\n" "parrot(voltage=1000) # 1つのキーワード引数\n" "parrot(voltage=1000000, action='VOOOOOM') # 2つのキーワード引数\n" "parrot(action='VOOOOOM', voltage=1000000) # 2つのキーワード引" "数 \n" "parrot('a million', 'bereft of life', 'jump') # 3つの位置引数\n" "parrot('a thousand', state='pushing up the daisies') # 1との位置引数と1つの" "キーワード引数" #: ../../tutorial/controlflow.rst:685 msgid "but all the following calls would be invalid::" msgstr "が、以下の呼び出しは不適切です::" #: ../../tutorial/controlflow.rst:687 msgid "" "parrot() # required argument missing\n" "parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword " "argument\n" "parrot(110, voltage=220) # duplicate value for the same argument\n" "parrot(actor='John Cleese') # unknown keyword argument" msgstr "" "parrot() # 必須の引数がない\n" "parrot(voltage=5.0, 'dead') # キーワード引数の後ろにキーワードのない引数\n" "parrot(110, voltage=220) # 同じ引数に対して2つの値を指定\n" "parrot(actor='John Cleese') # 未知のキーワード引数" #: ../../tutorial/controlflow.rst:692 msgid "" "In a function call, keyword arguments must follow positional arguments. All " "the keyword arguments passed must match one of the arguments accepted by the " "function (e.g. ``actor`` is not a valid argument for the ``parrot`` " "function), and their order is not important. This also includes non-" "optional arguments (e.g. ``parrot(voltage=1000)`` is valid too). No argument " "may receive a value more than once. Here's an example that fails due to this " "restriction::" msgstr "" "関数の呼び出しにおいて、キーワード引数は位置引数の後でなければなりません。渡" "されるキーワード引数は全て、関数で受け付けられる引数のいずれかに対応していな" "ければならず (例えば、``actor`` はこの ``parrot`` 関数の引数として適切ではあ" "りません)、順序は重要ではありません。これはオプションでない引数でも同様です " "(例えば、``parrot(voltage=1000)`` も適切です)。いかなる引数も値を複数回は受け" "取れません。この制限により失敗する例は::" #: ../../tutorial/controlflow.rst:700 msgid "" ">>> def function(a):\n" "... pass\n" "...\n" ">>> function(0, a=0)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: function() got multiple values for argument 'a'" msgstr "" ">>> def function(a):\n" "... pass\n" "...\n" ">>> function(0, a=0)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: function() got multiple values for argument 'a'" #: ../../tutorial/controlflow.rst:708 msgid "" "When a final formal parameter of the form ``**name`` is present, it receives " "a dictionary (see :ref:`typesmapping`) containing all keyword arguments " "except for those corresponding to a formal parameter. This may be combined " "with a formal parameter of the form ``*name`` (described in the next " "subsection) which receives a :ref:`tuple ` containing the " "positional arguments beyond the formal parameter list. (``*name`` must " "occur before ``**name``.) For example, if we define a function like this::" msgstr "" "仮引数の最後に ``**name`` の形式のものがあると、それまでの仮引数に対応したも" "のを除くすべてのキーワード引数が入った辞書 (:ref:`typesmapping` を参照) を受" "け取ります。\n" "``**name`` は ``*name`` の形式をとる、仮引数のリストを超えた位置引数の入っ" "た :ref:`タプル ` を受け取る引数 (次の小節で述べます) と組み合わ" "せられます。\n" "(``*name`` は ``**name`` より前になければなりません)。\n" "例えば、ある関数の定義を以下のようにすると::" #: ../../tutorial/controlflow.rst:716 msgid "" "def cheeseshop(kind, *arguments, **keywords):\n" " print(\"-- Do you have any\", kind, \"?\")\n" " print(\"-- I'm sorry, we're all out of\", kind)\n" " for arg in arguments:\n" " print(arg)\n" " print(\"-\" * 40)\n" " for kw in keywords:\n" " print(kw, \":\", keywords[kw])" msgstr "" "def cheeseshop(kind, *arguments, **keywords):\n" " print(\"-- Do you have any\", kind, \"?\")\n" " print(\"-- I'm sorry, we're all out of\", kind)\n" " for arg in arguments:\n" " print(arg)\n" " print(\"-\" * 40)\n" " for kw in keywords:\n" " print(kw, \":\", keywords[kw])" #: ../../tutorial/controlflow.rst:725 msgid "It could be called like this::" msgstr "呼び出しは以下のようになり::" #: ../../tutorial/controlflow.rst:727 msgid "" "cheeseshop(\"Limburger\", \"It's very runny, sir.\",\n" " \"It's really very, VERY runny, sir.\",\n" " shopkeeper=\"Michael Palin\",\n" " client=\"John Cleese\",\n" " sketch=\"Cheese Shop Sketch\")" msgstr "" "cheeseshop(\"Limburger\", \"It's very runny, sir.\",\n" " \"It's really very, VERY runny, sir.\",\n" " shopkeeper=\"Michael Palin\",\n" " client=\"John Cleese\",\n" " sketch=\"Cheese Shop Sketch\")" #: ../../tutorial/controlflow.rst:733 msgid "and of course it would print:" msgstr "もちろん以下のように出力されます:" #: ../../tutorial/controlflow.rst:735 msgid "" "-- Do you have any Limburger ?\n" "-- I'm sorry, we're all out of Limburger\n" "It's very runny, sir.\n" "It's really very, VERY runny, sir.\n" "----------------------------------------\n" "shopkeeper : Michael Palin\n" "client : John Cleese\n" "sketch : Cheese Shop Sketch" msgstr "" "-- Do you have any Limburger ?\n" "-- I'm sorry, we're all out of Limburger\n" "It's very runny, sir.\n" "It's really very, VERY runny, sir.\n" "----------------------------------------\n" "shopkeeper : Michael Palin\n" "client : John Cleese\n" "sketch : Cheese Shop Sketch" #: ../../tutorial/controlflow.rst:746 msgid "" "Note that the order in which the keyword arguments are printed is guaranteed " "to match the order in which they were provided in the function call." msgstr "" "なお、複数のキーワード引数を与えた場合に、それらが出力される順序は、関数呼び" "出しで与えられた順序と同じになります。" #: ../../tutorial/controlflow.rst:750 msgid "Special parameters" msgstr "特殊なパラメータ" #: ../../tutorial/controlflow.rst:752 msgid "" "By default, arguments may be passed to a Python function either by position " "or explicitly by keyword. For readability and performance, it makes sense to " "restrict the way arguments can be passed so that a developer need only look " "at the function definition to determine if items are passed by position, by " "position or keyword, or by keyword." msgstr "" "デフォルトでは、引数は位置またはキーワードによる明示で Python 関数に渡されま" "す。\n" "可読性とパフォーマンスのために、その引数が位置、位置またはキーワード、キー" "ワードのどれで渡されるかを開発者が判定するのに関数定義だけを見ればよいよう" "に、引数の渡され方を制限することには意味があります。" #: ../../tutorial/controlflow.rst:758 msgid "A function definition may look like:" msgstr "関数定義は次のようになります:" #: ../../tutorial/controlflow.rst:760 msgid "" "def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):\n" " ----------- ---------- ----------\n" " | | |\n" " | Positional or keyword |\n" " | - Keyword only\n" " -- Positional only" msgstr "" "def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):\n" " ----------- ---------- ----------\n" " | | |\n" " | 位置またはキーワード |\n" " | - キーワード専用\n" " -- 位置専用" #: ../../tutorial/controlflow.rst:769 msgid "" "where ``/`` and ``*`` are optional. If used, these symbols indicate the kind " "of parameter by how the arguments may be passed to the function: positional-" "only, positional-or-keyword, and keyword-only. Keyword parameters are also " "referred to as named parameters." msgstr "" "ここで、``/`` と ``*`` はオプションです。使用された場合、これらの記号は、引数" "が関数に渡される方法、すなわち、位置専用、位置またはキーワード、キーワード専" "用、といった引数の種類を示します。キーワード引数は、名前付き引数とも呼ばれま" "す。" #: ../../tutorial/controlflow.rst:776 msgid "Positional-or-Keyword Arguments" msgstr "位置またはキーワード引数" #: ../../tutorial/controlflow.rst:778 msgid "" "If ``/`` and ``*`` are not present in the function definition, arguments may " "be passed to a function by position or by keyword." msgstr "" "関数定義に ``/`` も ``*`` もない場合は、引数は位置またはキーワードで関数に渡" "されます。" #: ../../tutorial/controlflow.rst:783 msgid "Positional-Only Parameters" msgstr "位置専用引数" #: ../../tutorial/controlflow.rst:785 msgid "" "Looking at this in a bit more detail, it is possible to mark certain " "parameters as *positional-only*. If *positional-only*, the parameters' order " "matters, and the parameters cannot be passed by keyword. Positional-only " "parameters are placed before a ``/`` (forward-slash). The ``/`` is used to " "logically separate the positional-only parameters from the rest of the " "parameters. If there is no ``/`` in the function definition, there are no " "positional-only parameters." msgstr "" "これをもう少し詳しく見てみると、特定の引数を *位置専用* と印を付けられま" "す。\n" "*位置専用* の場合、引数の順序が重要であり、キーワードで引数を渡せません。\n" "位置専用引数は ``/`` (スラッシュ)の前に配置されます。\n" "``/`` は、位置専用引数を残りの引数から論理的に分離するために使用されます。\n" "関数定義に ``/`` がない場合、位置専用引数はありません。" #: ../../tutorial/controlflow.rst:793 msgid "" "Parameters following the ``/`` may be *positional-or-keyword* or *keyword-" "only*." msgstr "" "``/`` の後の引数は、 *位置またはキーワード* 、もしくは、 *キーワード専用* で" "す。" #: ../../tutorial/controlflow.rst:797 msgid "Keyword-Only Arguments" msgstr "キーワード専用引数" #: ../../tutorial/controlflow.rst:799 msgid "" "To mark parameters as *keyword-only*, indicating the parameters must be " "passed by keyword argument, place an ``*`` in the arguments list just before " "the first *keyword-only* parameter." msgstr "" "引数をキーワード引数で渡す必要があることを示す *キーワード専用* として引数を" "マークするには、引数リストの最初の *キーワード専用* 引数の直前に ``*`` を配" "置します。" #: ../../tutorial/controlflow.rst:805 msgid "Function Examples" msgstr "関数の例" #: ../../tutorial/controlflow.rst:807 msgid "" "Consider the following example function definitions paying close attention " "to the markers ``/`` and ``*``::" msgstr "" "``/`` および ``*`` といったマーカーに注意を払って、次の関数定義の例を見てくだ" "さい::" #: ../../tutorial/controlflow.rst:810 msgid "" ">>> def standard_arg(arg):\n" "... print(arg)\n" "...\n" ">>> def pos_only_arg(arg, /):\n" "... print(arg)\n" "...\n" ">>> def kwd_only_arg(*, arg):\n" "... print(arg)\n" "...\n" ">>> def combined_example(pos_only, /, standard, *, kwd_only):\n" "... print(pos_only, standard, kwd_only)" msgstr "" ">>> def standard_arg(arg):\n" "... print(arg)\n" "...\n" ">>> def pos_only_arg(arg, /):\n" "... print(arg)\n" "...\n" ">>> def kwd_only_arg(*, arg):\n" "... print(arg)\n" "...\n" ">>> def combined_example(pos_only, /, standard, *, kwd_only):\n" "... print(pos_only, standard, kwd_only)" #: ../../tutorial/controlflow.rst:823 msgid "" "The first function definition, ``standard_arg``, the most familiar form, " "places no restrictions on the calling convention and arguments may be passed " "by position or keyword::" msgstr "" "最も馴染みのある形式の最初の関数定義 ``standard_arg`` は、呼び出し規約に制限" "を設けておらず、引数は位置またはキーワードで渡されます::" #: ../../tutorial/controlflow.rst:827 msgid "" ">>> standard_arg(2)\n" "2\n" "\n" ">>> standard_arg(arg=2)\n" "2" msgstr "" ">>> standard_arg(2)\n" "2\n" "\n" ">>> standard_arg(arg=2)\n" "2" #: ../../tutorial/controlflow.rst:833 msgid "" "The second function ``pos_only_arg`` is restricted to only use positional " "parameters as there is a ``/`` in the function definition::" msgstr "" "2番目の関数の ``pos_only_arg`` は、 ``/`` が関数定義にあるので、引数は位置専" "用になります::" #: ../../tutorial/controlflow.rst:836 msgid "" ">>> pos_only_arg(1)\n" "1\n" "\n" ">>> pos_only_arg(arg=1)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: pos_only_arg() got some positional-only arguments passed as " "keyword arguments: 'arg'" msgstr "" ">>> pos_only_arg(1)\n" "1\n" "\n" ">>> pos_only_arg(arg=1)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: pos_only_arg() got some positional-only arguments passed as " "keyword arguments: 'arg'" #: ../../tutorial/controlflow.rst:844 msgid "" "The third function ``kwd_only_arg`` only allows keyword arguments as " "indicated by a ``*`` in the function definition::" msgstr "" "3番目の関数 ``kwd_only_arg`` は、関数定義に ``*`` があるので、引数はキーワー" "ド専用になります::" #: ../../tutorial/controlflow.rst:847 msgid "" ">>> kwd_only_arg(3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given\n" "\n" ">>> kwd_only_arg(arg=3)\n" "3" msgstr "" ">>> kwd_only_arg(3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given\n" "\n" ">>> kwd_only_arg(arg=3)\n" "3" #: ../../tutorial/controlflow.rst:855 msgid "" "And the last uses all three calling conventions in the same function " "definition::" msgstr "" "そして最後の関数は3つの引数の種類を一つの関数定義の中で使用しています::" #: ../../tutorial/controlflow.rst:858 msgid "" ">>> combined_example(1, 2, 3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: combined_example() takes 2 positional arguments but 3 were given\n" "\n" ">>> combined_example(1, 2, kwd_only=3)\n" "1 2 3\n" "\n" ">>> combined_example(1, standard=2, kwd_only=3)\n" "1 2 3\n" "\n" ">>> combined_example(pos_only=1, standard=2, kwd_only=3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: combined_example() got some positional-only arguments passed as " "keyword arguments: 'pos_only'" msgstr "" ">>> combined_example(1, 2, 3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: combined_example() takes 2 positional arguments but 3 were given\n" "\n" ">>> combined_example(1, 2, kwd_only=3)\n" "1 2 3\n" "\n" ">>> combined_example(1, standard=2, kwd_only=3)\n" "1 2 3\n" "\n" ">>> combined_example(pos_only=1, standard=2, kwd_only=3)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: combined_example() got some positional-only arguments passed as " "keyword arguments: 'pos_only'" #: ../../tutorial/controlflow.rst:875 msgid "" "Finally, consider this function definition which has a potential collision " "between the positional argument ``name`` and ``**kwds`` which has ``name`` " "as a key::" msgstr "" "最後に、位置引数 ``name`` と ``name`` をキーとして持つ ``**kwds`` の間に潜在" "的な衝突がある関数定義を考えてみましょう。" #: ../../tutorial/controlflow.rst:877 msgid "" "def foo(name, **kwds):\n" " return 'name' in kwds" msgstr "" "def foo(name, **kwds):\n" " return 'name' in kwds" #: ../../tutorial/controlflow.rst:880 msgid "" "There is no possible call that will make it return ``True`` as the keyword " "``'name'`` will always bind to the first parameter. For example::" msgstr "" "キーワードに ``'name'`` を入れても、先頭の引数と同じになってしまうため、この" "関数が ``True`` を返すような呼び出しの方法はありません。例えば、次のように" "なってしまいます::" #: ../../tutorial/controlflow.rst:883 msgid "" ">>> foo(1, **{'name': 2})\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: foo() got multiple values for argument 'name'\n" ">>>" msgstr "" ">>> foo(1, **{'name': 2})\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: foo() got multiple values for argument 'name'\n" ">>>" #: ../../tutorial/controlflow.rst:889 msgid "" "But using ``/`` (positional only arguments), it is possible since it allows " "``name`` as a positional argument and ``'name'`` as a key in the keyword " "arguments::" msgstr "" "しかし位置専用を示す ``/`` を使用すれば可能になります。 ``name`` は位置引数と" "して、そして ``'name'`` はキーワード引数のキーワードとして認識されるからで" "す::" #: ../../tutorial/controlflow.rst:891 msgid "" ">>> def foo(name, /, **kwds):\n" "... return 'name' in kwds\n" "...\n" ">>> foo(1, **{'name': 2})\n" "True" msgstr "" ">>> def foo(name, /, **kwds):\n" "... return 'name' in kwds\n" "...\n" ">>> foo(1, **{'name': 2})\n" "True" #: ../../tutorial/controlflow.rst:897 msgid "" "In other words, the names of positional-only parameters can be used in " "``**kwds`` without ambiguity." msgstr "" "言い換えると、位置専用引数であれば、その名前を ``**kwds`` の中で使用しても、" "曖昧にならないということです。" #: ../../tutorial/controlflow.rst:902 msgid "Recap" msgstr "要約" #: ../../tutorial/controlflow.rst:904 msgid "" "The use case will determine which parameters to use in the function " "definition::" msgstr "使用例で、関数定義でどの種類の引数を使うかべきかがわかると思います::" #: ../../tutorial/controlflow.rst:906 msgid "def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):" msgstr "def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):" #: ../../tutorial/controlflow.rst:908 msgid "As guidance:" msgstr "ガイドとしては、" #: ../../tutorial/controlflow.rst:910 msgid "" "Use positional-only if you want the name of the parameters to not be " "available to the user. This is useful when parameter names have no real " "meaning, if you want to enforce the order of the arguments when the function " "is called or if you need to take some positional parameters and arbitrary " "keywords." msgstr "" "もし引数の名前をユーザーに知らせる必要がないなら、位置専用引数を使用しましょ" "う。これは引数の名前がユーザーにとって意味がなく、関数が呼ばれたときの引数の" "順序が問題であり、または、位置引数と任意のキーワードを使用する必要がある場合" "に便利です。" #: ../../tutorial/controlflow.rst:915 msgid "" "Use keyword-only when names have meaning and the function definition is more " "understandable by being explicit with names or you want to prevent users " "relying on the position of the argument being passed." msgstr "" "引数の名前に意味があり、それにより関数の定義がより明らかになる、または、ユー" "ザーが引数の順番に縛られることを避けたほうがいいと考えるのなら、キーワード専" "用引数を使用しましょう。" #: ../../tutorial/controlflow.rst:918 msgid "" "For an API, use positional-only to prevent breaking API changes if the " "parameter's name is modified in the future." msgstr "" "APIの場合、将来引数の名前が変更された場合にAPIの変更ができなくなることを防ぐ" "ために、位置専用引数を使用しましょう。" #: ../../tutorial/controlflow.rst:924 msgid "Arbitrary Argument Lists" msgstr "任意引数リスト" #: ../../tutorial/controlflow.rst:929 msgid "" "Finally, the least frequently used option is to specify that a function can " "be called with an arbitrary number of arguments. These arguments will be " "wrapped up in a tuple (see :ref:`tut-tuples`). Before the variable number " "of arguments, zero or more normal arguments may occur. ::" msgstr "" "最後に、最も使うことの少ない選択肢として、関数が任意の個数の引数で呼び出せる" "よう指定する方法があります。これらの引数はタプル (:ref:`tut-tuples` を参照) " "に格納されます。可変個の引数の前に、ゼロ個かそれ以上の引数があっても構いませ" "ん。 ::" #: ../../tutorial/controlflow.rst:934 msgid "" "def write_multiple_items(file, separator, *args):\n" " file.write(separator.join(args))" msgstr "" "def write_multiple_items(file, separator, *args):\n" " file.write(separator.join(args))" #: ../../tutorial/controlflow.rst:938 msgid "" "Normally, these *variadic* arguments will be last in the list of formal " "parameters, because they scoop up all remaining input arguments that are " "passed to the function. Any formal parameters which occur after the " "``*args`` parameter are 'keyword-only' arguments, meaning that they can only " "be used as keywords rather than positional arguments. ::" msgstr "" "通常このような *可変* 引数は、関数に渡される入力引数の残りを全て掬い取るため" "に、仮引数リストの最後に置かれます。\n" "``*args`` 引数の後にある仮引数は 'キーワード専用' 引数で、位置引数ではなく" "キーワード引数としてのみ使えることを意味します。 ::" #: ../../tutorial/controlflow.rst:944 msgid "" ">>> def concat(*args, sep=\"/\"):\n" "... return sep.join(args)\n" "...\n" ">>> concat(\"earth\", \"mars\", \"venus\")\n" "'earth/mars/venus'\n" ">>> concat(\"earth\", \"mars\", \"venus\", sep=\".\")\n" "'earth.mars.venus'" msgstr "" ">>> def concat(*args, sep=\"/\"):\n" "... return sep.join(args)\n" "...\n" ">>> concat(\"earth\", \"mars\", \"venus\")\n" "'earth/mars/venus'\n" ">>> concat(\"earth\", \"mars\", \"venus\", sep=\".\")\n" "'earth.mars.venus'" #: ../../tutorial/controlflow.rst:955 msgid "Unpacking Argument Lists" msgstr "引数リストのアンパック" #: ../../tutorial/controlflow.rst:957 msgid "" "The reverse situation occurs when the arguments are already in a list or " "tuple but need to be unpacked for a function call requiring separate " "positional arguments. For instance, the built-in :func:`range` function " "expects separate *start* and *stop* arguments. If they are not available " "separately, write the function call with the ``*``\\ -operator to unpack " "the arguments out of a list or tuple::" msgstr "" "引数がすでにリストやタプルになっていて、個別な位置引数を要求する関数呼び出し" "に渡すためにアンパックする必要がある場合には、逆の状況が起こります。例えば、" "組み込み関数 :func:`range` は引数 *start* と *stop* を別に与える必要がありま" "す。個別に引数を与えることができない場合、関数呼び出しを ``*`` 演算子を使って" "書き、リストやタプルから引数をアンパックします::" #: ../../tutorial/controlflow.rst:964 msgid "" ">>> list(range(3, 6)) # normal call with separate arguments\n" "[3, 4, 5]\n" ">>> args = [3, 6]\n" ">>> list(range(*args)) # call with arguments unpacked from a " "list\n" "[3, 4, 5]" msgstr "" ">>> list(range(3, 6)) # 個別に引数を指定する通常の関数呼び出し\n" "[3, 4, 5]\n" ">>> args = [3, 6]\n" ">>> list(range(*args)) # 引数リストをアンパックして関数呼び出し\n" "[3, 4, 5]" #: ../../tutorial/controlflow.rst:973 msgid "" "In the same fashion, dictionaries can deliver keyword arguments with the " "``**``\\ -operator::" msgstr "" "同じやりかたで、``**`` オペレータを使って辞書でもキーワード引数を渡すことがで" "きます::" #: ../../tutorial/controlflow.rst:976 msgid "" ">>> def parrot(voltage, state='a stiff', action='voom'):\n" "... print(\"-- This parrot wouldn't\", action, end=' ')\n" "... print(\"if you put\", voltage, \"volts through it.\", end=' ')\n" "... print(\"E's\", state, \"!\")\n" "...\n" ">>> d = {\"voltage\": \"four million\", \"state\": \"bleedin' demised\", " "\"action\": \"VOOM\"}\n" ">>> parrot(**d)\n" "-- This parrot wouldn't VOOM if you put four million volts through it. E's " "bleedin' demised !" msgstr "" ">>> def parrot(voltage, state='a stiff', action='voom'):\n" "... print(\"-- This parrot wouldn't\", action, end=' ')\n" "... print(\"if you put\", voltage, \"volts through it.\", end=' ')\n" "... print(\"E's\", state, \"!\")\n" "...\n" ">>> d = {\"voltage\": \"four million\", \"state\": \"bleedin' demised\", " "\"action\": \"VOOM\"}\n" ">>> parrot(**d)\n" "-- This parrot wouldn't VOOM if you put four million volts through it. E's " "bleedin' demised !" #: ../../tutorial/controlflow.rst:989 msgid "Lambda Expressions" msgstr "ラムダ式" #: ../../tutorial/controlflow.rst:991 msgid "" "Small anonymous functions can be created with the :keyword:`lambda` keyword. " "This function returns the sum of its two arguments: ``lambda a, b: a+b``. " "Lambda functions can be used wherever function objects are required. They " "are syntactically restricted to a single expression. Semantically, they are " "just syntactic sugar for a normal function definition. Like nested function " "definitions, lambda functions can reference variables from the containing " "scope::" msgstr "" "キーワード :keyword:`lambda` を使うと、名前のない小さな関数を生成できます。例" "えば ``lambda a, b: a+b`` は、二つの引数の和を返す関数です。ラムダ式の関数" "は、関数オブジェクトが要求されている場所にならどこでも使うことができます。ラ" "ムダ式は、構文上単一の式に制限されています。意味付け的には、ラムダ形式は単に" "通常の関数定義に構文的な糖衣をかぶせたものに過ぎません。入れ子構造になった関" "数定義と同様、ラムダ式もそれを取り囲むスコープから変数を参照することができま" "す::" #: ../../tutorial/controlflow.rst:999 msgid "" ">>> def make_incrementor(n):\n" "... return lambda x: x + n\n" "...\n" ">>> f = make_incrementor(42)\n" ">>> f(0)\n" "42\n" ">>> f(1)\n" "43" msgstr "" ">>> def make_incrementor(n):\n" "... return lambda x: x + n\n" "...\n" ">>> f = make_incrementor(42)\n" ">>> f(0)\n" "42\n" ">>> f(1)\n" "43" #: ../../tutorial/controlflow.rst:1008 msgid "" "The above example uses a lambda expression to return a function. Another " "use is to pass a small function as an argument. For instance, :meth:`list." "sort` takes a sorting key function *key* which can be a lambda function::" msgstr "" "上記の例ではラムダ式を使って関数を返しています。 別の使い方としては、小さな" "関数を引数として渡すこともできます。 たとえば、 :meth:`list.sort` はソート" "キー関数 *key* を受け取りますが、これにはラムダ関数を渡せます::" #: ../../tutorial/controlflow.rst:1012 msgid "" ">>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]\n" ">>> pairs.sort(key=lambda pair: pair[1])\n" ">>> pairs\n" "[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]" msgstr "" ">>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]\n" ">>> pairs.sort(key=lambda pair: pair[1])\n" ">>> pairs\n" "[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]" #: ../../tutorial/controlflow.rst:1021 msgid "Documentation Strings" msgstr "ドキュメンテーション文字列" #: ../../tutorial/controlflow.rst:1028 msgid "" "Here are some conventions about the content and formatting of documentation " "strings." msgstr "" "ドキュメンテーション文字列については、その内容と書式に関する慣習をいくつか挙" "げます。" #: ../../tutorial/controlflow.rst:1031 msgid "" "The first line should always be a short, concise summary of the object's " "purpose. For brevity, it should not explicitly state the object's name or " "type, since these are available by other means (except if the name happens " "to be a verb describing a function's operation). This line should begin " "with a capital letter and end with a period." msgstr "" "最初の行は、常に対象物の目的を短く簡潔にまとめたものでなくてはなりません。簡" "潔に書くために、対象物の名前や型を明示する必要はありません。名前や型は他の方" "法でも得られるからです (名前がたまたま関数の演算内容を記述する動詞である場合" "は例外です)。最初の行は大文字で始まり、ピリオドで終わっていなければなりませ" "ん。" #: ../../tutorial/controlflow.rst:1037 msgid "" "If there are more lines in the documentation string, the second line should " "be blank, visually separating the summary from the rest of the description. " "The following lines should be one or more paragraphs describing the object's " "calling conventions, its side effects, etc." msgstr "" "ドキュメンテーション文字列中にさらに記述すべき行がある場合、二行目は空行に" "し、まとめの行と残りの記述部分を視覚的に分離します。つづく行は一つまたはそれ" "以上の段落で、対象物の呼び出し規約や副作用について記述します。" #: ../../tutorial/controlflow.rst:1042 msgid "" "The Python parser strips indentation from multi-line string literals when " "they serve as module, class, or function docstrings." msgstr "" #: ../../tutorial/controlflow.rst:1045 msgid "Here is an example of a multi-line docstring::" msgstr "以下に複数行のドキュメンテーション文字列の例を示します::" #: ../../tutorial/controlflow.rst:1047 msgid "" ">>> def my_function():\n" "... \"\"\"Do nothing, but document it.\n" "...\n" "... No, really, it doesn't do anything:\n" "...\n" "... >>> my_function()\n" "... >>>\n" "... \"\"\"\n" "... pass\n" "...\n" ">>> print(my_function.__doc__)\n" "Do nothing, but document it.\n" "\n" "No, really, it doesn't do anything:\n" "\n" " >>> my_function()\n" " >>>" msgstr "" ">>> def my_function():\n" "... \"\"\"なにもしないがドキュメントは書く。\n" "...\n" "... 本当になにもしない。\n" "...\n" "... >>> my_function()\n" "... >>>\n" "... \"\"\"\n" "... pass\n" "...\n" ">>> print(my_function.__doc__)\n" "なにもしないがドキュメントは書く。\n" "\n" "本当になにもしない。\n" "\n" " >>> my_function()\n" " >>>" #: ../../tutorial/controlflow.rst:1069 msgid "Function Annotations" msgstr "関数のアノテーション" #: ../../tutorial/controlflow.rst:1077 msgid "" ":ref:`Function annotations ` are completely optional metadata " "information about the types used by user-defined functions (see :pep:`3107` " "and :pep:`484` for more information)." msgstr "" ":ref:`関数アノテーション ` はユーザ定義関数で使用される型についての" "完全にオプションなメタデータ情報です (詳細は :pep:`3107` と :pep:`484` を参照" "してください)。" #: ../../tutorial/controlflow.rst:1081 msgid "" ":term:`Annotations ` are stored in the :attr:`~object." "__annotations__` attribute of the function as a dictionary and have no " "effect on any other part of the function. Parameter annotations are defined " "by a colon after the parameter name, followed by an expression evaluating to " "the value of the annotation. Return annotations are defined by a literal ``-" ">``, followed by an expression, between the parameter list and the colon " "denoting the end of the :keyword:`def` statement. The following example has " "a required argument, an optional argument, and the return value annotated::" msgstr "" ":term:`アノテーション ` は関数の :attr:`~object." "__annotations__` 属性に辞書として格納され、関数の他の部分には何も影響を与えま" "せん。パラメータアノテーションは、パラメータ名の後にコロンを続けることによっ" "て定義され、その後にアノテーションの値として評価される式が置かれます。戻り値" "アノテーションは、パラメータリストと :keyword:`def` 文の終わりを表すコロンの" "間に置かれたリテラル ``->`` によって定義され、その後に式が続きます。次の例は" "必須の引数とオプション引数、そして戻り値のアノテーションを持っています::" #: ../../tutorial/controlflow.rst:1090 msgid "" ">>> def f(ham: str, eggs: str = 'eggs') -> str:\n" "... print(\"Annotations:\", f.__annotations__)\n" "... print(\"Arguments:\", ham, eggs)\n" "... return ham + ' and ' + eggs\n" "...\n" ">>> f('spam')\n" "Annotations: {'ham': , 'return': , 'eggs': }\n" "Arguments: spam eggs\n" "'spam and eggs'" msgstr "" ">>> def f(ham: str, eggs: str = 'eggs') -> str:\n" "... print(\"Annotations:\", f.__annotations__)\n" "... print(\"Arguments:\", ham, eggs)\n" "... return ham + ' and ' + eggs\n" "...\n" ">>> f('spam')\n" "アノテーション: {'ham': , 'return': , 'eggs': " "}\n" "引数: spam eggs\n" "'spam and eggs'" #: ../../tutorial/controlflow.rst:1103 msgid "Intermezzo: Coding Style" msgstr "間奏曲: コーディングスタイル" #: ../../tutorial/controlflow.rst:1108 msgid "" "Now that you are about to write longer, more complex pieces of Python, it is " "a good time to talk about *coding style*. Most languages can be written (or " "more concisely, *formatted*) in different styles; some are more readable " "than others. Making it easy for others to read your code is always a good " "idea, and adopting a nice coding style helps tremendously for that." msgstr "" #: ../../tutorial/controlflow.rst:1114 msgid "" "For Python, :pep:`8` has emerged as the style guide that most projects " "adhere to; it promotes a very readable and eye-pleasing coding style. Every " "Python developer should read it at some point; here are the most important " "points extracted for you:" msgstr "" "Python には、ほとんどのプロジェクトが守っているスタイルガイドとして :pep:`8` " "があります。それは非常に読み易く目に優しいコーディングスタイルを推奨していま" "す。全ての Python 開発者はある時点でそれを読むべきです。ここに最も重要な点を" "抜き出しておきます:" #: ../../tutorial/controlflow.rst:1119 msgid "Use 4-space indentation, and no tabs." msgstr "インデントには空白 4 つを使い、タブは使わないこと。" #: ../../tutorial/controlflow.rst:1121 msgid "" "4 spaces are a good compromise between small indentation (allows greater " "nesting depth) and large indentation (easier to read). Tabs introduce " "confusion, and are best left out." msgstr "" "空白 4 つは (深くネストできる) 小さいインデントと (読み易い) 大きいインデント" "のちょうど中間に当たります。タブは混乱させるので、使わずにおくのが良いです。" #: ../../tutorial/controlflow.rst:1125 msgid "Wrap lines so that they don't exceed 79 characters." msgstr "ソースコードの幅が 79 文字を越えないように行を折り返すこと。" #: ../../tutorial/controlflow.rst:1127 msgid "" "This helps users with small displays and makes it possible to have several " "code files side-by-side on larger displays." msgstr "" "こうすることで小さいディスプレイを使っているユーザも読み易くなり、大きなディ" "スプレイではソースコードファイルを並べることもできるようになります。" #: ../../tutorial/controlflow.rst:1130 msgid "" "Use blank lines to separate functions and classes, and larger blocks of code " "inside functions." msgstr "関数やクラスや関数内の大きめのコードブロックの区切りに空行を使うこと。" #: ../../tutorial/controlflow.rst:1133 msgid "When possible, put comments on a line of their own." msgstr "可能なら、コメントは行に独立で書くこと。" #: ../../tutorial/controlflow.rst:1135 msgid "Use docstrings." msgstr "docstring を使うこと。" #: ../../tutorial/controlflow.rst:1137 msgid "" "Use spaces around operators and after commas, but not directly inside " "bracketing constructs: ``a = f(1, 2) + g(3, 4)``." msgstr "" "演算子の前後とコンマの後には空白を入れ、括弧類のすぐ内側には空白を入れないこ" "と: ``a = f(1, 2) + g(3, 4)``。" #: ../../tutorial/controlflow.rst:1140 msgid "" "Name your classes and functions consistently; the convention is to use " "``UpperCamelCase`` for classes and ``lowercase_with_underscores`` for " "functions and methods. Always use ``self`` as the name for the first method " "argument (see :ref:`tut-firstclasses` for more on classes and methods)." msgstr "" "クラスや関数に一貫性のある名前を付けること。慣習では ``UpperCamelCase`` をク" "ラス名に使い、 ``lowercase_with_underscores`` を関数名やメソッド名に使いま" "す。常に ``self`` をメソッドの第 1 引数の名前 (クラスやメソッドについては :" "ref:`tut-firstclasses` を見よ) として使うこと。" #: ../../tutorial/controlflow.rst:1145 msgid "" "Don't use fancy encodings if your code is meant to be used in international " "environments. Python's default, UTF-8, or even plain ASCII work best in any " "case." msgstr "" "あなたのコードを世界中で使ってもらうつもりなら、風変りなエンコーディングは使" "わないこと。どんな場合でも、Python のデフォルト UTF-8 またはプレーン ASCII が" "最も上手くいきます。" #: ../../tutorial/controlflow.rst:1149 msgid "" "Likewise, don't use non-ASCII characters in identifiers if there is only the " "slightest chance people speaking a different language will read or maintain " "the code." msgstr "" "同様に、ほんの少しでも他の言語を話す人がコードを読んだりメンテナンスする可能" "性があるのであれば、非 ASCII 文字も識別子に使うべきではありません。" #: ../../tutorial/controlflow.rst:1155 msgid "Footnotes" msgstr "脚注" #: ../../tutorial/controlflow.rst:1156 msgid "" "Actually, *call by object reference* would be a better description, since if " "a mutable object is passed, the caller will see any changes the callee makes " "to it (items inserted into a list)." msgstr "" "実のところ、*オブジェクトへの参照渡し (call by object reference)* という言っ" "たほうがより正確です。というのは、変更可能なオブジェクトが渡されると、呼び出" "された側の関数がオブジェクトに行った変更 (例えばリストに挿入された要素) はす" "べて、関数の呼び出し側にも反映されるからです。" #: ../../tutorial/controlflow.rst:48 msgid "statement" msgstr "statement" #: ../../tutorial/controlflow.rst:48 msgid "for" msgstr "for" #: ../../tutorial/controlflow.rst:254 msgid "..." msgstr "..." #: ../../tutorial/controlflow.rst:254 msgid "ellipsis literal" msgstr "ellipsisリテラル" #: ../../tutorial/controlflow.rst:485 ../../tutorial/controlflow.rst:1023 msgid "documentation strings" msgstr "documentation strings" #: ../../tutorial/controlflow.rst:485 ../../tutorial/controlflow.rst:1023 msgid "docstrings" msgstr "docstrings" #: ../../tutorial/controlflow.rst:485 ../../tutorial/controlflow.rst:1023 msgid "strings, documentation" msgstr "strings, documentation" #: ../../tutorial/controlflow.rst:926 msgid "* (asterisk)" msgstr "* (アスタリスク)" #: ../../tutorial/controlflow.rst:926 ../../tutorial/controlflow.rst:970 msgid "in function calls" msgstr "関数呼び出しの中の" #: ../../tutorial/controlflow.rst:970 msgid "**" msgstr "**" #: ../../tutorial/controlflow.rst:1072 msgid "function" msgstr "関数" #: ../../tutorial/controlflow.rst:1072 msgid "annotations" msgstr "annotations" #: ../../tutorial/controlflow.rst:1072 msgid "->" msgstr "->" #: ../../tutorial/controlflow.rst:1072 msgid "function annotations" msgstr "関数のアノテーション" #: ../../tutorial/controlflow.rst:1072 msgid ": (colon)" msgstr ": (コロン)" #: ../../tutorial/controlflow.rst:1106 msgid "coding" msgstr "coding" #: ../../tutorial/controlflow.rst:1106 msgid "style" msgstr "style"