# Copyright (C) 2001-2024, Python Software Foundation # This file is distributed under the same license as the Python package. # # Translators: # Liang-Bo Wang , 2015 # Liang-Bo Wang , 2016 # hsiao yi , 2015 # Steven Hsu , 2021-2022 msgid "" msgstr "" "Project-Id-Version: Python 3.13\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-06-27 07:36+0000\n" "PO-Revision-Date: 2022-07-24 14:52+0800\n" "Last-Translator: Steven Hsu \n" "Language-Team: Chinese - TAIWAN (https://github.com/python/python-docs-zh-" "tw)\n" "Language: zh_TW\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" "X-Generator: Poedit 3.1.1\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 中的慣用方式。相" "較於只能疊代 (iterate) 一個等差數列(如 Pascal),或給予使用者定義疊代步驟與" "終止條件(如 C),Python 的 :keyword:`!for` 陳述式疊代任何序列(list 或者字" "串)的元素,順序與它們出現在序列中的順序相同。例如(無意雙關): ::" #: ../../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 "" "在疊代一個集合的同時修改該集合的內容,很難取得想要的結果。比較直觀的替代方" "式,是疊代該集合的副本,或建立一個新的集合: ::" #: ../../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` 回傳的物件表現得像是一個 list(串列)一樣,但" "實際上它並不是。它是一個在疊代時能夠回傳所要求的序列中所有項目的物件,但它不" "會真正建出這個序列的 list,以節省空間。" #: ../../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:`iterable`\\ (可疊代物件),意即能作為函式及架構中" "可以一直取得項目直到取盡的對象。我們已經了解 :keyword:`for` 陳述式就是如此的" "架構,另一個使用 iterable 的函式範例是 :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 in more detail " "about :func:`list`." msgstr "" "待會我們可以看到更多回傳 iterable 和使用 iterable 為引數的函式。在\\ :ref:" "`tut-structures`\\ 章節中,我們會討論更多關於 :func:`list` 的細節。" #: ../../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` 陳述式,終止包含它的最內部 :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} 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" #: ../../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\"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" #: ../../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` 子句會在迴圈完成最終的疊代後執行。" #: ../../tutorial/controlflow.rst:211 msgid "" "In a :keyword:`while` loop, it's executed after the loop's condition becomes " "false." msgstr "在 :keyword:`while` 迴圈中,它會在迴圈條件變為 false 後執行。" #: ../../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, 'equals', x, '*', n//x)\n" "... break\n" "... else:\n" "... # 迴圈結束但沒有找到因數\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" #: ../../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`` 子句屬於 ``for`` 迴圈,**並非** " "``if`` 陳述式。)" #: ../../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 "" "理解 else 子句的一個方法是將它想像成與迴圈內的 ``if`` 配對。當迴圈執行時,它會" "運行如 if/if/if/else 的序列。``if`` 在迴圈內,會遇到多次。如果條件曾經為真," "``break`` 就會發生。如果條件從未為真,迴圈外的 ``else`` 子句就會執行。" #: ../../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`` 陳述式使用,它的行為與 :" "keyword:`try` 陳述式中的 ``else`` 子句更為相似:``try`` 陳述式的 ``else`` 子" "句在沒有發生例外 (exception) 時執行,而迴圈的 ``else`` 子句在沒有任何 " "``break`` 發生時執行。更多有關 ``try`` 陳述式和例外的介紹,見\\ :ref:`tut-" "handling`。" #: ../../tutorial/controlflow.rst:257 msgid ":keyword:`!pass` Statements" msgstr ":keyword:`!pass` 陳述式" #: ../../tutorial/controlflow.rst:259 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` 陳述式不執行任何動作。它可用在語法上需要一個陳述式但程式不需" "要執行任何動作的時候。例如: ::" #: ../../tutorial/controlflow.rst:262 msgid "" ">>> while True:\n" "... pass # Busy-wait for keyboard interrupt (Ctrl+C)\n" "..." msgstr "" ">>> while True:\n" "... pass # 忙碌等待鍵盤中斷 (Ctrl+C)\n" "..." #: ../../tutorial/controlflow.rst:266 msgid "This is commonly used for creating minimal classes::" msgstr "這經常用於建立簡單的 class(類別): ::" #: ../../tutorial/controlflow.rst:268 msgid "" ">>> class MyEmptyClass:\n" "... pass\n" "..." msgstr "" ">>> class MyEmptyClass:\n" "... pass\n" "..." #: ../../tutorial/controlflow.rst:272 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` 亦可作為一個函式或條件判斷主體的預留位置,在你撰寫新的程式碼" "時讓你保持在更抽象的思維層次。:keyword:`!pass` 會直接被忽略: ::" #: ../../tutorial/controlflow.rst:276 msgid "" ">>> def initlog(*args):\n" "... pass # Remember to implement this!\n" "..." msgstr "" ">>> def initlog(*args):\n" "... pass # 記得要實作這個!\n" "..." #: ../../tutorial/controlflow.rst:284 msgid ":keyword:`!match` Statements" msgstr ":keyword:`!match` 陳述式" #: ../../tutorial/controlflow.rst:286 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." msgstr "" ":keyword:`match` 陳述式會拿取一個運算式,並將其值與多個連續的模式 (pattern) " "進行比較,這些模式是以一個或多個 case 區塊來表示。表面上,這類似 C、Java 或 " "JavaScript(以及許多其他語言)中的 switch 陳述式,但它與 Rust 或 Haskell 等語" "言中的模式匹配 (pattern matching) 更為相近。只有第一個匹配成功的模式會被執" "行,而它也可以將成分(序列元素或物件屬性)從值中提取到變數中。" #: ../../tutorial/controlflow.rst:294 msgid "" "The simplest form compares a subject value against one or more literals::" msgstr "" "最簡單的形式,是將一個主題值 (subject value) 與一個或多個字面值 (literal) 進" "行比較: ::" #: ../../tutorial/controlflow.rst:296 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:307 msgid "" "Note the last block: the \"variable name\" ``_`` acts as a *wildcard* and " "never fails to match. If no case matches, none of the branches is executed." msgstr "" "請注意最後一段:「變數名稱」\\ ``_`` 是作為\\ *通用字元 (wildcard)*\\ 的角" "色,且永遠不會匹配失敗。如果沒有 case 匹配成功,則不會執行任何的分支。" #: ../../tutorial/controlflow.rst:310 msgid "" "You can combine several literals in a single pattern using ``|`` (\"or\")::" msgstr "你可以使用 ``|``\\ (「或」)來將多個字面值組合在單一模式中: ::" #: ../../tutorial/controlflow.rst:312 msgid "" "case 401 | 403 | 404:\n" " return \"Not allowed\"" msgstr "" "case 401 | 403 | 404:\n" " return \"Not allowed\"" #: ../../tutorial/controlflow.rst:315 msgid "" "Patterns can look like unpacking assignments, and can be used to bind " "variables::" msgstr "" "模式可以看起來像是拆解賦值 (unpacking assignment),且可以用來連結變數: ::" #: ../../tutorial/controlflow.rst:318 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(\"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\")" #: ../../tutorial/controlflow.rst:331 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 "" "請仔細研究那個例子!第一個模式有兩個字面值,可以想作是之前所述的字面值模式的" "延伸。但是接下來的兩個模式結合了一個字面值和一個變數,且該變數\\ *繫結 " "(bind)* 了來自主題 (``point``) 的一個值。第四個模式會擷取兩個值,這使得它在概" "念上類似於拆解賦值 ``(x, y) = point``。" #: ../../tutorial/controlflow.rst:338 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 "" "如果你要用 class 來結構化你的資料,你可以使用該 class 的名稱加上一個引數列" "表,類似一個建構式 (constructor),但它能夠將屬性擷取到變數中: ::" #: ../../tutorial/controlflow.rst:342 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(\"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\")" #: ../../tutorial/controlflow.rst:360 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 "" "你可以將位置參數 (positional parameter) 與一些能夠排序其屬性的內建 class(例" "如 dataclasses)一起使用。你也可以透過在 class 中設定特殊屬性 " "``__match_args__``,來定義模式中屬性們的特定位置。如果它被設定為 (\"x\", " "\"y\"),則以下的模式都是等價的(且都會將屬性 ``y`` 連結到變數 ``var``): ::" #: ../../tutorial/controlflow.rst:366 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:371 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 "" "理解模式的一種推薦方法,是將它們看作是你會放在賦值 (assignment) 左側內容的一" "種延伸形式,這樣就可以了解哪些變數會被設為何值。只有獨立的名稱(像是上面的 " "``var``)能被 match 陳述式賦值。點分隔名稱(如 ``foo.bar``)、屬性名稱(上面" "的 ``x=`` 及 ``y=``)或 class 名稱(由它們後面的 \"(...)\" 被辨識,如上面的 " "``Point``)則永遠無法被賦值。" #: ../../tutorial/controlflow.rst:378 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 "" "模式可以任意地被巢套 (nested)。例如,如果我們有一個由某些點所組成的簡短 " "list,我們就可以像這樣加入 ``__match_args__`` 來對它進行匹配: ::" #: ../../tutorial/controlflow.rst:381 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(\"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\")" #: ../../tutorial/controlflow.rst:399 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`` 子句,稱為「防護 (guard)」。如果該防護為假," "則 ``match`` 會繼續嘗試下一個 case 區塊。請注意,值的擷取會發生在防護的評估之" "前: ::" #: ../../tutorial/controlflow.rst:403 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\"Not on the diagonal\")" #: ../../tutorial/controlflow.rst:409 msgid "Several other key features of this statement:" msgstr "此種陳述式的其他幾個重要特色:" #: ../../tutorial/controlflow.rst:411 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 "" "與拆解賦值的情況類似,tuple(元組)和 list 模式具有完全相同的意義,而且實際上" "可以匹配任意的序列。一個重要的例外,是它們不能匹配疊代器 (iterator) 或字串。" #: ../../tutorial/controlflow.rst:415 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 "" "序列模式 (sequence pattern) 可支援擴充拆解 (extended unpacking):``[x, y, " "*rest]`` 與 ``(x, y, *rest)`` 的作用類似於拆解賦值。``*`` 後面的名稱也可以是 " "``_``,所以 ``(x, y, *_)`` 會匹配一個至少兩項的序列,且不會連結那兩項以外的其" "餘項。" #: ../../tutorial/controlflow.rst:420 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 "" "對映模式 (mapping pattern):``{\"bandwidth\": b, \"latency\": l}`` 能從一個 " "dictionary(字典)中擷取 ``\"bandwidth\"`` 及 ``\"latency\"`` 的值。與序列模" "式不同,額外的鍵 (key) 會被忽略。一種像是 ``**rest`` 的拆解方式,也是可被支援" "的。(但 ``**_`` 則是多餘的做法,所以它並不被允許。)" #: ../../tutorial/controlflow.rst:425 msgid "Subpatterns may be captured using the ``as`` keyword::" msgstr "使用關鍵字 ``as`` 可以擷取子模式 (subpattern): ::" #: ../../tutorial/controlflow.rst:427 msgid "case (Point(x1, y1), Point(x2, y2) as p2): ..." msgstr "case (Point(x1, y1), Point(x2, y2) as p2): ..." #: ../../tutorial/controlflow.rst:429 msgid "" "will capture the second element of the input as ``p2`` (as long as the input " "is a sequence of two points)" msgstr "" "將會擷取輸入的第二個元素作為 ``p2``\\ (只要該輸入是一個由兩個點所組成的序" "列)。" #: ../../tutorial/controlflow.rst:432 msgid "" "Most literals are compared by equality, however the singletons ``True``, " "``False`` and ``None`` are compared by identity." msgstr "" "大部分的字面值是藉由相等性 (equality) 來比較,但是單例物件 (singleton) " "``True``、``False`` 和 ``None`` 是藉由標識值 (identity) 來比較。" #: ../../tutorial/controlflow.rst:435 msgid "" "Patterns may use named constants. These must be dotted names to prevent " "them from being interpreted as capture variable::" msgstr "" "模式可以使用附名常數 (named constant)。這些模式必須是點分隔名稱,以免它們被解" "釋為擷取變數: ::" #: ../../tutorial/controlflow.rst:438 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:454 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:460 msgid "Defining Functions" msgstr "定義函式 (function)" #: ../../tutorial/controlflow.rst:462 msgid "" "We can create a function that writes the Fibonacci series to an arbitrary " "boundary::" msgstr "我們可以建立一個函式來產生費式數列到任何一個上界: ::" #: ../../tutorial/controlflow.rst:465 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 的費氏數列。\"\"\"\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:482 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` 介紹一個函式的\\ *定義*。它之後必須連著該函式的名稱和置" "於括號之中的一串參數。自下一行起,所有縮排的陳述式成為該函式的主體。" #: ../../tutorial/controlflow.rst:487 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 "" "一個函式的第一個陳述式可以是一個字串文本;該字串文本被視為該函式的說明文件字" "串,即 :dfn:`docstring`。(關於 docstring 的細節請參見\\ :ref:`tut-" "docstrings`\\ 段落。)有些工具可以使用 docstring 來自動產生線上或可列印的文" "件,或讓使用者能以互動的方式在原始碼中瀏覽文件。在原始碼中加入 docstring 是個" "好慣例,應該養成這樣的習慣。" #: ../../tutorial/controlflow.rst:494 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 "" "函式\\ *執行*\\ 時會建立一個新的符號表 (symbol table) 來儲存該函式內的區域變" "數 (local variable)。更精確地說,所有在函式內的變數賦值都會把該值儲存在一個區" "域符號表。然而,在引用一個變數時,會先從區域符號表開始搜尋,其次為外層函式的" "區域符號表,其次為全域符號表 (global symbol table),最後為所有內建的名稱。因" "此,在函式中,全域變數及外層函式變數雖然可以被引用,但無法被直接賦值(除非全" "域變數是在 :keyword:`global` 陳述式中被定義,或外層函式變數在 :keyword:" "`nonlocal` 陳述式中被定義)。" #: ../../tutorial/controlflow.rst:505 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)*\\ (這裡傳遞的\\ *值*\\ " "永遠是一個物件的\\ *參照 (reference)*,而不是該物件的值)。 [#]_ 當一個函式呼" "叫別的函式或遞迴呼叫它自己時,在被呼叫的函式中會建立一個新的區域符號表。" #: ../../tutorial/controlflow.rst:512 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:517 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:523 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:530 msgid "" ">>> fib(0)\n" ">>> print(fib(0))\n" "None" msgstr "" ">>> fib(0)\n" ">>> print(fib(0))\n" "None" #: ../../tutorial/controlflow.rst:534 msgid "" "It is simple to write a function that returns a list of the numbers of the " "Fibonacci series, instead of printing it::" msgstr "如果要寫一個函式回傳費式數列的 list 而不是直接印出它,這也很容易: ::" #: ../../tutorial/controlflow.rst:537 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:550 msgid "This example, as usual, demonstrates some new Python features:" msgstr "這個例子一樣示範了一些新的 Python 特性:" #: ../../tutorial/controlflow.rst:552 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:556 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:`!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)`` 陳述式呼叫了一個 list 物件 ``result`` 的 *method(方法)" "*。method 為「屬於」一個物件的函式,命名規則為 ``obj.methodname``,其中 " "``obj`` 為某個物件(亦可為一運算式),而 ``methodname`` 為該 method 的名稱," "並由該物件的型別所定義。不同的型別定義不同的 method。不同型別的 method 可以擁" "有一樣的名稱而不會讓 Python 混淆。(你可以使用 *class*\\ (類別)定義自己的物" "件型別和 method,見 :ref:`tut-classes`\\ )範例中的 :meth:`!append` method 定" "義在 list 物件中;它會在該 list 的末端加入一個新的元素。這個例子等同於 " "``result = result + [a]``,但更有效率。" #: ../../tutorial/controlflow.rst:571 msgid "More on Defining Functions" msgstr "深入了解函式定義" #: ../../tutorial/controlflow.rst:573 msgid "" "It is also possible to define functions with a variable number of arguments. " "There are three forms, which can be combined." msgstr "" "定義函式時使用的引數 (argument) 數量是可變的。總共有三種可以組合使用的形式。" #: ../../tutorial/controlflow.rst:580 msgid "Default Argument Values" msgstr "預設引數值" #: ../../tutorial/controlflow.rst:582 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:586 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='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)" #: ../../tutorial/controlflow.rst:598 msgid "This function can be called in several ways:" msgstr "該函式可以用以下幾種方式被呼叫:" #: ../../tutorial/controlflow.rst:600 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:602 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:604 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:607 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:610 msgid "" "The default values are evaluated at the point of function definition in the " "*defining* scope, so that ::" msgstr "預設值是在函式定義當下,於\\ *定義時*\\ 的作用域中求值,所以: ::" #: ../../tutorial/controlflow.rst:613 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:621 msgid "will print ``5``." msgstr "將會輸出 ``5``。" #: ../../tutorial/controlflow.rst:623 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 "" "\\ **重要警告**:預設值只求值一次。當預設值為可變物件,例如 list、dictionary" "(字典)或許多類別實例時,會產生不同的結果。例如,以下函式於後續呼叫時會累積" "曾經傳遞的引數: ::" #: ../../tutorial/controlflow.rst:628 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:636 msgid "This will print ::" msgstr "將會輸出: ::" #: ../../tutorial/controlflow.rst:638 msgid "" "[1]\n" "[1, 2]\n" "[1, 2, 3]" msgstr "" "[1]\n" "[1, 2]\n" "[1, 2, 3]" #: ../../tutorial/controlflow.rst:642 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:645 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:655 msgid "Keyword Arguments" msgstr "關鍵字引數" #: ../../tutorial/controlflow.rst:657 msgid "" "Functions can also be called using :term:`keyword arguments ` of the form ``kwarg=value``. For instance, the following " "function::" msgstr "" "函式也可以使用\\ :term:`關鍵字引數 `,以 ``kwarg=value`` 的" "形式呼叫。舉例來說,以下函式: ::" #: ../../tutorial/controlflow.rst:660 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:666 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:670 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 個關鍵字引數\n" #: ../../tutorial/controlflow.rst:677 msgid "but all the following calls would be invalid::" msgstr "但以下呼叫方式都無效: ::" #: ../../tutorial/controlflow.rst:679 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) # 同一個引數有重複值\n" "parrot(actor='John Cleese') # 未知的關鍵字引數" #: ../../tutorial/controlflow.rst:684 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 "" "函式呼叫時,關鍵字引數 (keyword argument) 必須在位置引數 (positional " "argument) 後面。所有傳遞的關鍵字引數都必須匹配一個可被函式接受的引數(\\ " "``actor`` 不是 ``parrot`` 函式的有效引數),而關鍵字引數的順序並不重要。此規" "則也包括必要引數,(\\ ``parrot(voltage=1000)`` 也有效)。一個引數不可多次被" "賦值,下面就是一個因此限制而無效的例子: ::" #: ../../tutorial/controlflow.rst:692 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:700 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`` 形式時,它接收一個 dictionary(字典,詳見 :ref:" "`typesmapping`\\ ),該字典包含所有可對應形式參數以外的關鍵字引數。" "``**name`` 可以與 ``*name`` 參數(下一小節介紹)組合使用,``*name`` 接收一" "個 :ref:`tuple `,該 tuple 包含一般參數以外的位置引數(\\ " "``*name`` 必須出現在 ``**name`` 前面)。例如,若我們定義這樣的函式: ::" #: ../../tutorial/controlflow.rst:708 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:717 msgid "It could be called like this::" msgstr "它可以被如此呼叫: ::" #: ../../tutorial/controlflow.rst:719 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:725 msgid "and of course it would print:" msgstr "輸出結果如下: ::" #: ../../tutorial/controlflow.rst:727 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:738 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:742 msgid "Special parameters" msgstr "特殊參數" #: ../../tutorial/controlflow.rst:744 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 函式。為了程式的可讀性" "及效能,限制引數的傳遞方式是合理的,如此,開發者只需查看函式定義,即可確定各" "項目是按位置,按位置或關鍵字,還是按關鍵字傳遞。" #: ../../tutorial/controlflow.rst:750 msgid "A function definition may look like:" msgstr "函式定義可能如以下樣式:" #: ../../tutorial/controlflow.rst:752 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" " | Positional or keyword |\n" " | - Keyword only\n" " -- Positional only" #: ../../tutorial/controlflow.rst:761 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 "" "``/`` 和 ``*`` 是選擇性的。這些符號若被使用,是表明引數被傳遞給函式的參數種" "類:僅限位置、位置或關鍵字、僅限關鍵字。關鍵字參數也稱為附名參數 (named " "parameters)。" #: ../../tutorial/controlflow.rst:768 msgid "Positional-or-Keyword Arguments" msgstr "位置或關鍵字引數 (Positional-or-Keyword Arguments)" #: ../../tutorial/controlflow.rst:770 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:775 msgid "Positional-Only Parameters" msgstr "僅限位置參數 (Positional-Only Parameters)" #: ../../tutorial/controlflow.rst:777 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 "" "此處再詳述一些細節,特定參數可以標記為\\ *僅限位置*。若參數為\\ *僅限位置*\\ " "時,它們的順序很重要,且這些參數不能用關鍵字傳遞。僅限位置參數必須放在 ``/" "``\\ (斜線)之前。``/`` 用於在邏輯上分開僅限位置參數與其餘參數。如果函式定義" "中沒有 ``/``,則表示沒有任何僅限位置參數。" #: ../../tutorial/controlflow.rst:785 msgid "" "Parameters following the ``/`` may be *positional-or-keyword* or *keyword-" "only*." msgstr "``/`` 後面的參數可以是\\ *位置或關鍵字*\\ 或\\ *僅限關鍵字*\\ 參數。" #: ../../tutorial/controlflow.rst:789 msgid "Keyword-Only Arguments" msgstr "僅限關鍵字引數 (Keyword-Only Arguments)" #: ../../tutorial/controlflow.rst:791 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:797 msgid "Function Examples" msgstr "函式範例" #: ../../tutorial/controlflow.rst:799 msgid "" "Consider the following example function definitions paying close attention " "to the markers ``/`` and ``*``::" msgstr "請看以下的函式定義範例,注意 ``/`` 和 ``*`` 記號: ::" #: ../../tutorial/controlflow.rst:802 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:815 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:819 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:825 msgid "" "The second function ``pos_only_arg`` is restricted to only use positional " "parameters as there is a ``/`` in the function definition::" msgstr "" "第二個函式 ``pos_only_arg`` 的函式定義中有 ``/``,因此僅限使用位置參數: ::" #: ../../tutorial/controlflow.rst:828 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:836 msgid "" "The third function ``kwd_only_arg`` only allows keyword arguments as " "indicated by a ``*`` in the function definition::" msgstr "" "第三個函式 ``kwd_only_arg`` 的函式定義透過 ``*`` 表明僅限關鍵字引數: ::" #: ../../tutorial/controlflow.rst:839 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:847 msgid "" "And the last uses all three calling conventions in the same function " "definition::" msgstr "最後一個函式在同一個函式定義中,使用了全部三種呼叫方式: ::" #: ../../tutorial/controlflow.rst:850 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:867 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 "" "最後,請看這個函式定義,如果 ``**kwds`` 內有 ``name`` 這個鍵,可能與位置引數 " "``name`` 產生潛在衝突: ::" #: ../../tutorial/controlflow.rst:869 msgid "" "def foo(name, **kwds):\n" " return 'name' in kwds" msgstr "" "def foo(name, **kwds):\n" " return 'name' in kwds" #: ../../tutorial/controlflow.rst:872 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 "" "呼叫該函式不可能回傳 ``True``,因為關鍵字 ``'name'`` 永遠是連結在第一個參數。" "例如: ::" #: ../../tutorial/controlflow.rst:875 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:881 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:883 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:889 msgid "" "In other words, the names of positional-only parameters can be used in " "``**kwds`` without ambiguity." msgstr "換句話說,僅限位置參數的名稱可以在 ``**kwds`` 中使用,而不產生歧義。" #: ../../tutorial/controlflow.rst:894 msgid "Recap" msgstr "回顧" #: ../../tutorial/controlflow.rst:896 msgid "" "The use case will determine which parameters to use in the function " "definition::" msgstr "此用例決定哪些參數可以用於函式定義: ::" #: ../../tutorial/controlflow.rst:898 msgid "def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):" msgstr "def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):" #: ../../tutorial/controlflow.rst:900 msgid "As guidance:" msgstr "說明:" #: ../../tutorial/controlflow.rst:902 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:907 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:910 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:916 msgid "Arbitrary Argument Lists" msgstr "任意引數列表 (Arbitrary Argument Lists)" #: ../../tutorial/controlflow.rst:921 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 "" "最後,有個較不常用的選項,是規定函式被呼叫時,可以使用任意數量的引數。這些引" "數會被包裝進一個 tuple 中(詳見 :ref:`tut-tuples`\\ )。在可變數量的引數之" "前,可能有零個或多個普通引數: ::" #: ../../tutorial/controlflow.rst:926 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:930 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 "" "通常,這些 *variadic*\\ (可變的)引數會出現在參數列表的最末端,這樣它們就可" "以把所有傳遞給函式的剩餘輸入引數都撈起來。出現在 ``*args`` 參數後面的任何參數" "必須是「僅限關鍵字」引數,意即它們只能作為關鍵字引數,而不能用作位置引數。 ::" #: ../../tutorial/controlflow.rst:936 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:947 msgid "Unpacking Argument Lists" msgstr "拆解引數列表(Unpacking Argument Lists)" #: ../../tutorial/controlflow.rst:949 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 "" "當引數們已經存在一個 list 或 tuple 裡,但為了滿足一個需要個別位置引數的函式呼" "叫,而去拆解它們時,情況就剛好相反。例如,內建的 :func:`range` 函式要求分開" "的 *start* 和 *stop* 引數。如果這些引數不是分開的,則要在呼叫函式時,用 " "``*`` 運算子把引數們從 list 或 tuple 中拆解出來: ::" #: ../../tutorial/controlflow.rst:956 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:965 msgid "" "In the same fashion, dictionaries can deliver keyword arguments with the " "``**``\\ -operator::" msgstr "同樣地,dictionary(字典)可以用 ``**`` 運算子傳遞關鍵字引數: ::" #: ../../tutorial/controlflow.rst:968 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:981 msgid "Lambda Expressions" msgstr "Lambda 運算式" #: ../../tutorial/controlflow.rst:983 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`` 函式返回" "兩個引數的和。Lambda 函式可用於任何需要函式物件的地方。在語法上,它們被限定只" "能是單一運算式。在語義上,它就是一個普通函式定義的語法糖 (syntactic sugar)。" "與巢狀函式定義一樣,lambda 函式可以從包含它的作用域中引用變數: ::" #: ../../tutorial/controlflow.rst:991 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:1000 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 "" "上面的例子用 lambda 運算式回傳了一個函式。另外的用法是傳遞一個小函式當作引" "數。舉例來說,:meth:`list.sort` 接受一個鍵排序函式 *key*," "這個函式可以是 lambda 函式: ::" #: ../../tutorial/controlflow.rst:1004 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:1013 msgid "Documentation Strings" msgstr "說明文件字串 (Documentation Strings)" #: ../../tutorial/controlflow.rst:1020 msgid "" "Here are some conventions about the content and formatting of documentation " "strings." msgstr "以下是關於說明文件字串內容和格式的慣例。" #: ../../tutorial/controlflow.rst:1023 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:1029 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:1034 msgid "" "The Python parser does not strip indentation from multi-line string literals " "in Python, so tools that process documentation have to strip indentation if " "desired. This is done using the following convention. The first non-blank " "line *after* the first line of the string determines the amount of " "indentation for the entire documentation string. (We can't use the first " "line since it is generally adjacent to the string's opening quotes so its " "indentation is not apparent in the string literal.) Whitespace " "\"equivalent\" to this indentation is then stripped from the start of all " "lines of the string. Lines that are indented less should not occur, but if " "they occur all their leading whitespace should be stripped. Equivalence of " "whitespace should be tested after expansion of tabs (to 8 spaces, normally)." msgstr "" "Python 剖析器 (parser) 不會去除 Python 中多行字串的縮排,因此,處理說明文件的" "工具應在必要時去除縮排。這項操作遵循以下慣例:在字串第一行\\ *之後*\\ 的第一" "個非空白行決定了整個說明文件字串的縮排量(不能用第一行的縮排,因為它通常與字" "串的開頭引號們相鄰,其縮排在字串文本中並不明顯),然後,所有字串行開頭處與此" "縮排量「等價」的空白字元會被去除。不應出現比上述縮進量更少的字串行,但若真的" "出現了,這些行的全部前導空白字元都應被去除。展開 tab 鍵後(通常為八個空格)," "應測試空白字元量是否等價。" #: ../../tutorial/controlflow.rst:1046 msgid "Here is an example of a multi-line docstring::" msgstr "下面是多行說明字串的一個範例: ::" #: ../../tutorial/controlflow.rst:1048 msgid "" ">>> def my_function():\n" "... \"\"\"Do nothing, but document it.\n" "...\n" "... No, really, it doesn't do anything.\n" "... \"\"\"\n" "... pass\n" "...\n" ">>> print(my_function.__doc__)\n" "Do nothing, but document it.\n" "\n" "No, really, it doesn't do anything." msgstr "" ">>> def my_function():\n" "... \"\"\"不做任何事,但有文件說明。\n" "...\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." #: ../../tutorial/controlflow.rst:1064 msgid "Function Annotations" msgstr "函式註釋 (Function Annotations)" #: ../../tutorial/controlflow.rst:1072 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:`函式註釋 `\\ 是選擇性的元資料(metadata)資訊,描述使用者定義" "函式所使用的型別(更多資訊詳見 :pep:`3107` 和 :pep:`484`\\ )。" #: ../../tutorial/controlflow.rst:1076 msgid "" ":term:`Annotations ` are stored in the :attr:`!" "__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:`註釋 `\\ 以 dictionary(字典)的形式存放在函式" "的 :attr:`!__annotations__` 屬性中,且不會影響函式的任何其他部分。參數註釋的" "定義方式是在參數名稱後加一個冒號,冒號後面跟著一個對註釋求值的運算式。回傳註" "釋的定義方式是在參數列表和 :keyword:`def` 陳述式結尾的冒號中間,用一個 ``-" ">`` 文字接著一個運算式。以下範例註釋了一個必要引數、一個選擇性引數,以及回傳" "值: ::" #: ../../tutorial/controlflow.rst:1085 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" "Annotations: {'ham': , 'return': , 'eggs': }\n" "Arguments: spam eggs\n" "'spam and eggs'" #: ../../tutorial/controlflow.rst:1098 msgid "Intermezzo: Coding Style" msgstr "間奏曲:程式碼風格 (Coding Style)" #: ../../tutorial/controlflow.rst:1103 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 concise, *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 "" "現在你即將要寫更長、更複雜的 Python 程式,是時候討論一下\\ *編碼樣式*\\ 了。" "大多數語言都能以不同的樣式被書寫(或更精確地說,被\\ *格式化*\\ ),而有些樣" "式比其他的更具可讀性。能讓其他人輕鬆閱讀你的程式碼永遠是一個好主意,而使用優" "良的編碼樣式對此有極大的幫助。" #: ../../tutorial/controlflow.rst:1109 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:1114 msgid "Use 4-space indentation, and no tabs." msgstr "用 4 個空格縮排,不要用 tab 鍵。" #: ../../tutorial/controlflow.rst:1116 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 個空格是小縮排(容許更大的巢套深度)和大縮排(較易閱讀)之間的折衷方案。" "Tab 鍵會造成混亂,最好別用。" #: ../../tutorial/controlflow.rst:1120 msgid "Wrap lines so that they don't exceed 79 characters." msgstr "換行,使一行不超過 79 個字元。" #: ../../tutorial/controlflow.rst:1122 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:1125 msgid "" "Use blank lines to separate functions and classes, and larger blocks of code " "inside functions." msgstr "用空行分隔函式和 class(類別),及函式內較大塊的程式碼。" #: ../../tutorial/controlflow.rst:1128 msgid "When possible, put comments on a line of their own." msgstr "如果可以,把註解放在單獨一行。" #: ../../tutorial/controlflow.rst:1130 msgid "Use docstrings." msgstr "使用說明字串。" #: ../../tutorial/controlflow.rst:1132 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:1135 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 "" "Class 和函式的命名樣式要一致;按慣例,命名 class 用 ``UpperCamelCase``\\ (駝" "峰式大小寫),命名函式與 method 用 ``lowercase_with_underscores``\\ (小寫加" "底線)。永遠用 ``self`` 作為 method 第一個引數的名稱(關於 class 和 method," "詳見 :ref:`tut-firstclasses`\\ )。" #: ../../tutorial/controlflow.rst:1140 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:1144 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:1150 msgid "Footnotes" msgstr "註解" #: ../../tutorial/controlflow.rst:1151 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)* 的說法可能較為貼切。因為,若傳" "遞的是一個可變物件時,呼叫者將看得見被呼叫者對物件做出的任何改變(例如被插入 " "list 內的新項目)。" #: ../../tutorial/controlflow.rst:48 msgid "statement" msgstr "statement(陳述式)" #: ../../tutorial/controlflow.rst:48 msgid "for" msgstr "for" #: ../../tutorial/controlflow.rst:477 ../../tutorial/controlflow.rst:1015 msgid "documentation strings" msgstr "ddocumentation strings(說明字串)" #: ../../tutorial/controlflow.rst:477 ../../tutorial/controlflow.rst:1015 msgid "docstrings" msgstr "docstrings(說明字串)" #: ../../tutorial/controlflow.rst:477 ../../tutorial/controlflow.rst:1015 msgid "strings, documentation" msgstr "strings(字串), documentation(說明文件)" #: ../../tutorial/controlflow.rst:918 msgid "* (asterisk)" msgstr "* (星號)" #: ../../tutorial/controlflow.rst:918 ../../tutorial/controlflow.rst:962 msgid "in function calls" msgstr "於函式呼叫中" #: ../../tutorial/controlflow.rst:962 msgid "**" msgstr "**" #: ../../tutorial/controlflow.rst:1067 msgid "function" msgstr "function(函式)" #: ../../tutorial/controlflow.rst:1067 msgid "annotations" msgstr "annotations(註釋)" #: ../../tutorial/controlflow.rst:1067 msgid "->" msgstr "->" #: ../../tutorial/controlflow.rst:1067 msgid "function annotations" msgstr "function annotations(函式註釋)" #: ../../tutorial/controlflow.rst:1067 msgid ": (colon)" msgstr ": (冒號)" #: ../../tutorial/controlflow.rst:1101 msgid "coding" msgstr "coding(程式編寫)" #: ../../tutorial/controlflow.rst:1101 msgid "style" msgstr "style(風格)" #~ msgid "" #~ "A :keyword:`!for` or :keyword:`!while` loop can include an :keyword:`!" #~ "else` clause." #~ msgstr "" #~ ":keyword:`!for` 和 :keyword:`!while` 迴圈可帶有一個 :keyword:`!else` 子句"