Hướng dẫn dùng arithmetics definition python
This chapter explains the meaning of the elements of expressions in Python. Show
Nội dung chính
Nội dung chính
Nội dung chính
Syntax Notes: In this and the following chapters, extended BNF notation will be used to describe syntax, not lexical analysis. When (one alternative of) a syntax rule has the form name ::= and no semantics are given, the
semantics of this form of 6.1. Arithmetic conversions¶When a description of an arithmetic operator below uses the phrase “the numeric arguments are converted to a common type”, this means that the operator implementation for built-in types works as follows:
Some additional rules apply for certain operators (e.g., a string as a left argument to the ‘%’ operator). Extensions must define their own conversion behavior. 6.2. Atoms¶Atoms are the most basic elements of expressions. The simplest atoms are identifiers or literals. Forms enclosed in parentheses, brackets or braces are also categorized syntactically as atoms. The syntax for atoms is: atom ::= 6.2.1. Identifiers (Names)¶An identifier occurring as an atom is a name. See section Identifiers and keywords for lexical definition and section Naming and binding for documentation of naming and binding. When the name is bound to an object, evaluation of the atom yields
that object. When a name is not bound, an attempt to evaluate it raises a Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading
underscores removed and a single underscore inserted, in front of the name. For example, the identifier 6.2.2. Literals¶Python supports string and bytes literals and various numeric literals: literal ::= Evaluation of a literal yields an object of the given type (string, bytes, integer, floating point number, complex number) with the given value. The value may be approximated in the case of floating point and imaginary (complex) literals. See section Literals for details. All literals correspond to immutable data types, and hence the object’s identity is less important than its value. Multiple evaluations of literals with the same value (either the same occurrence in the program text or a different occurrence) may obtain the same object or a different object with the same value. 6.2.3. Parenthesized forms¶A parenthesized form is an optional expression list enclosed in parentheses: parenth_form ::= "(" [ A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list. An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the same rules as for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object). Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught. 6.2.4. Displays for lists, sets and dictionaries¶For constructing a list, a set or a dictionary Python provides special syntax called “displays”, each of them in two flavors:
Common syntax elements for comprehensions are: comprehension ::= The comprehension consists of a single expression followed by at least one However, aside from the iterable expression in the leftmost The iterable expression in the leftmost To ensure the comprehension always results in a container of the appropriate type, Since Python 3.6, in an New in version 3.6: Asynchronous comprehensions were introduced. Changed in version 3.8: 6.2.5. List displays¶A list display is a possibly empty series of expressions enclosed in square brackets: list_display ::= "[" [ A list display yields a new list object, the contents being specified by either a list of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and placed into the list object in that order. When a comprehension is supplied, the list is constructed from the elements resulting from the comprehension. 6.2.6. Set displays¶A set display is denoted by curly braces and distinguishable from dictionary displays by the lack of colons separating keys and values: set_display ::= "{" ( A set display yields a new mutable set object, the contents being specified by either a sequence of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and added to the set object. When a comprehension is supplied, the set is constructed from the elements resulting from the comprehension. An empty set cannot be constructed with 6.2.7. Dictionary displays¶A dictionary display is a possibly empty series of key/datum pairs enclosed in curly braces: dict_display ::= "{" [ A dictionary display yields a new dictionary object. If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum. This means that you can specify the same key multiple times in the key/datum list, and the final dictionary’s value for that key will be the last one given. A double asterisk New in version 3.5: Unpacking into dictionary displays, originally proposed by PEP 448. A dict comprehension, in contrast to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses. When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced. Restrictions on the types of the key values are listed earlier in section The standard type hierarchy. (To summarize, the key type should be hashable, which excludes all mutable objects.) Clashes between duplicate keys are not detected; the last datum (textually rightmost in the display) stored for a given key value prevails. Changed in version 3.8: Prior to Python 3.8, in dict comprehensions, the evaluation order of key and value was not well-defined. In CPython, the value was evaluated before the key. Starting with 3.8, the key is evaluated before the value, as proposed by PEP 572. 6.2.8. Generator expressions¶A generator expression is a compact generator notation in parentheses: generator_expression ::= "(" A generator expression yields a new generator object. Its syntax is the same as for comprehensions, except that it is enclosed in parentheses instead of brackets or curly braces. Variables used in the generator expression are
evaluated lazily when the The parentheses can be omitted on calls with only one argument. See section Calls for details. To avoid interfering with the expected operation of the generator expression itself, If a generator expression contains either New in version 3.6: Asynchronous generator expressions were introduced. Changed in version 3.7: Prior to Python 3.7, asynchronous generator expressions could only appear in Changed in version 3.8: 6.2.9. Yield expressions¶yield_atom ::= "(" The yield expression is used when defining a generator function or an asynchronous generator function and thus can only be used in the body of a function definition. Using a yield expression in a function’s body causes that function to be a
generator function, and using it in an def gen(): # defines a generator function yield 123 async def agen(): # defines an asynchronous generator function yield 123 Due to their side effects on the containing scope, Changed in version 3.8: Yield expressions prohibited in the implicitly nested scopes used to implement comprehensions and generator expressions. Generator functions are described below, while asynchronous generator functions are described separately in section Asynchronous generator functions. When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of the generator function. The execution starts when one of the generator’s methods is called. At that time, the execution proceeds to the first yield expression, where it is
suspended again, returning the value of All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than one entry point and their execution can be suspended. The only difference is that a generator function cannot control where the execution should continue after it yields; the control is always transferred to the generator’s caller. Yield expressions are allowed anywhere in a When When the underlying iterator is complete, the
The parentheses may be omitted when the yield expression is the sole expression on the right hand side of an assignment statement. See also PEP 255 - Simple GeneratorsThe proposal for adding generators and the The proposal to enhance the API and syntax of generators, making them usable as simple coroutines. PEP 380 - Syntax for Delegating to a SubgeneratorThe proposal to introduce the The proposal that expanded on PEP 492 by adding generator capabilities to coroutine functions. 6.2.9.1. Generator-iterator methods¶This subsection describes the methods of a generator iterator. They can be used to control the execution of a generator function. Note that calling any of the generator methods below when the generator is already executing raises a generator. __next__ ()¶Starts the execution of a generator function or resumes it at the last executed yield expression. When a generator function is resumed with a This method is normally called implicitly, e.g. by a generator. send (value)¶Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The generator. throw (value)¶ generator. throw (type[, value[, traceback]])Raises an exception at the point where the generator was paused, and returns the next value yielded by the generator function.
If the generator exits without yielding another value, a In typical use, this is called with a single exception instance similar to the way the For backwards compatibility, however, the second signature is supported, following a convention from older versions of Python. The type
argument should be an exception class, and value should be an exception instance. If the value is not provided, the type constructor is called to get an instance. If traceback is provided, it is set on the exception, otherwise any existing generator. close ()¶Raises a 6.2.9.2. Examples¶Here is a simple example that demonstrates the behavior of generators and generator functions: >>> def echo(value=None): ... print("Execution starts when 'next()' is called for the first time.") ... try: ... while True: ... try: ... value = (yield value) ... except Exception as e: ... value = e ... finally: ... print("Don't forget to clean up when 'close()' is called.") ... >>> generator = echo(1) >>> print(next(generator)) Execution starts when 'next()' is called for the first time. 1 >>> print(next(generator)) None >>> print(generator.send(2)) 2 >>> generator.throw(TypeError, "spam") TypeError('spam',) >>> generator.close() Don't forget to clean up when 'close()' is called. For
examples using 6.2.9.3. Asynchronous generator functions¶The presence of a yield expression in a function or method defined using When an asynchronous generator function is called, it returns an asynchronous iterator known as an
asynchronous generator object. That object then controls the execution of the generator function. An asynchronous generator object is typically used in an Calling one of the asynchronous generator’s methods returns an awaitable object, and the execution starts when this object is awaited on. At that time, the execution proceeds to the first yield expression,
where it is suspended again, returning the value of If an asynchronous generator happens to exit early by In an asynchronous generator function, yield expressions are allowed anywhere in a To take care of finalization upon event
loop termination, an event loop should define a finalizer function which takes an asynchronous generator-iterator and presumably calls The expression 6.2.9.4. Asynchronous generator-iterator methods¶This subsection describes the methods of an asynchronous generator iterator, which are used to control the execution of a generator function. coroutineagen. __anext__ ()¶Returns an awaitable which when run starts to execute the asynchronous generator or resumes it
at the last executed yield expression. When an asynchronous generator function is resumed with an This method is normally called implicitly by a agen. asend (value)¶Returns an awaitable which when run resumes the execution of the asynchronous generator. As with the agen. athrow (type[, value[,
traceback]])¶Returns an awaitable that raises an exception of type agen. aclose ()¶Returns an awaitable that when run will throw a 6.3. Primaries¶Primaries represent the most tightly bound operations of the language. Their syntax is: primary ::= 6.3.1. Attribute references¶An attribute reference is a primary followed by a period and a name: attributeref ::= The primary must evaluate to an object of a type that supports attribute references, which most objects do. This object is then asked to produce the
attribute whose name is the identifier. This production can be customized by overriding the 6.3.2. Subscriptions¶The subscription of an instance of a container class will generally select an element from the container. The subscription of a generic class will generally return a GenericAlias object. subscription ::= When an object is subscripted, the interpreter will evaluate the primary and the expression list. The primary must evaluate to an object that supports subscription. An object may support subscription through defining one or both of If the expression list contains at least one comma, it will evaluate to a For built-in objects, there are two types of objects that support
subscription via
The formal syntax makes no special provision for negative indices in sequences. However, built-in sequences all provide a A 6.3.3. Slicings¶A slicing selects a range of items in a sequence object (e.g., a string, tuple or list). Slicings may be used as expressions or as targets in assignment or slicing ::= There is ambiguity in the formal syntax here: anything that looks like an expression list also looks like a slice list, so any subscription can be interpreted as a slicing. Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the slice list contains no proper slice). The semantics for a slicing are as follows. The primary is indexed (using the same 6.3.4. Calls¶A call calls a callable object (e.g., a function) with a possibly empty series of arguments: call ::= An optional trailing comma may be present after the positional and keyword arguments but does not affect the semantics. The primary must evaluate to a callable object (user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances, and all objects having a If keyword arguments are present, they are first converted to positional arguments, as follows. First, a list of unfilled slots is created for the formal parameters. If there are N positional arguments, they are placed in the first N slots. Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the
identifier is the same as the first formal parameter name, the first slot is used, and so on). If the slot is already filled, a CPython implementation detail: An implementation may provide built-in functions
whose positional parameters do not have names, even if they are ‘named’ for the purpose of documentation, and which therefore cannot be supplied by keyword. In CPython, this is the case for functions implemented in C that use If there are more positional arguments than there are formal parameter slots, a If any keyword argument does not correspond to a formal parameter name, a If the syntax A consequence of this is that although the >>> def f(a, b): ... print(a, b) ... >>> f(b=1, *(2,)) 2 1 >>> f(a=1, *(2,)) Traceback (most recent call last): File " It is unusual for both keyword arguments and the If the syntax Formal parameters using the syntax Changed in version 3.5: Function calls accept any number of A call
always returns some value, possibly If it is— a user-defined function:The code block for the function is executed, passing it the argument list. The first thing the code block will do is bind the formal parameters to the arguments; this is described in section Function definitions. When the code block executes a The result is up to the interpreter; see Built-in Functions for the descriptions of built-in functions and methods. a class object:A new instance of that class is returned. a class instance method:The corresponding user-defined function is called, with an argument list that is one longer than the argument list of the call: the instance becomes the first argument. a class instance:The class must define
a 6.4. Await expression¶Suspend the execution of coroutine on an awaitable object. Can only be used inside a coroutine function. await_expr ::= "await" New in version 3.5. 6.5. The power operator¶The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is: power ::= ( Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): The power operator has the same semantics as the built-in For int operands, the result has the same type as the operands unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, Raising This operation can be customized using the special 6.6. Unary arithmetic and bitwise operations¶All unary arithmetic and bitwise operations have the same priority: u_expr ::= The unary The unary The unary In all three cases, if the argument does not have the
proper type, a 6.7. Binary arithmetic operations¶The binary arithmetic operations have the conventional priority levels. Note that some of these operations also apply to certain non-numeric types. Apart from the power operator, there are only two levels, one for multiplicative operators and one for additive operators: m_expr ::= The This operation can be customized using the special The New in version 3.5. The This operation can be customized using the special The The floor division and modulo operators are connected by the following identity: In addition to performing the modulo operation on numbers, the The modulo operation can be customized using the special The floor division operator, the modulo operator, and the The This operation can be customized using the special The This operation can be customized
using the special 6.8. Shifting operations¶The shifting operations have lower priority than the arithmetic operations: shift_expr ::= These operators accept integers as arguments. They shift the first argument to the left or right by the number of bits given by the second argument. This operation can be customized using the special A right shift by n bits is
defined as floor division by 6.9. Binary bitwise operations¶Each of the three bitwise operations has a different priority level: and_expr ::= The The The 6.10. Comparisons¶Unlike C, all comparison operations in Python
have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like comparison ::= Comparisons yield boolean values: Comparisons can be chained arbitrarily, e.g., Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then Note that 6.10.1. Value comparisons¶The operators Chapter Objects, values and types states that objects have a value (in addition to type and identity). The value of an object is a rather abstract notion in Python: For example, there is no canonical access method for an object’s value. Also, there is no requirement that the value of an object should be constructed in a particular way, e.g. comprised of all its data attributes. Comparison operators implement a particular notion of what the value of an object is. One can think of them as defining the value of an object indirectly, by means of their comparison implementation. Because all types are (direct or indirect) subtypes of The default behavior for equality comparison ( A default order comparison ( The behavior of the default equality comparison, that instances with different identities are always unequal, may be in contrast to what types will need that have a sensible definition of object value and value-based equality. Such types will need to customize their comparison behavior, and in fact, a number of built-in types have done that. The following list describes the comparison behavior of the most important built-in types.
User-defined classes that customize their comparison behavior should follow some consistency rules, if possible:
Python does not enforce these consistency rules. In fact, the not-a-number values are an example for not following these rules. 6.10.2. Membership test operations¶The operators For the string and bytes types, For user-defined classes which define the For user-defined
classes which do not define Lastly, the old-style iteration protocol is tried: if a class defines The operator 6.10.3. Identity comparisons¶The operators 6.11. Boolean operations¶or_test ::= In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: The operator The expression The expression Note that neither 6.12. Assignment expressions¶assignment_expression ::= [ An assignment expression (sometimes also called a “named expression” or “walrus”) assigns an One common use case is when handling matched regular expressions: if matching := pattern.search(data): do_something(matching) Or, when processing a file stream in chunks: while chunk := file.read(9000): process(chunk) New in version 3.8: See PEP 572 for more details about assignment expressions. 6.13. Conditional expressions¶conditional_expression ::= Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations. The expression See PEP 308 for more details about conditional expressions. 6.14. Lambdas¶lambda_expr ::= "lambda" [ Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. The expression def See section Function definitions for the syntax of parameter lists. Note that functions created with lambda expressions cannot contain statements or annotations. 6.15. Expression lists¶expression_list ::= Except when part of a list or set display, an expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right. An asterisk New in version 3.5: Iterable unpacking in expression lists, originally proposed by PEP 448. The trailing comma is required only to create a single tuple (a.k.a. a singleton); it is optional in all other cases. A single expression without a trailing comma doesn’t create a
tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses: 6.16. Evaluation order¶Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side. In the following lines, expressions will be evaluated in the arithmetic order of their suffixes: expr1, expr2, expr3, expr4 (expr1, expr2, expr3, expr4) {expr1: expr2, expr3: expr4} expr1 + expr2 * (expr3 - expr4) expr1(expr2, expr3, *expr4, **expr5) expr3, expr4 = expr1, expr2 6.17. Operator precedence¶The following table summarizes the operator precedence in Python, from highest precedence (most binding) to lowest precedence (least binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation, which groups from right to left). Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.
Footnotes 1While If x is very close to an exact integer multiple of y, it’s possible for The Unicode standard distinguishes between code points (e.g. U+0041) and abstract characters (e.g. “LATIN CAPITAL LETTER A”). While most abstract characters in Unicode are only represented using one code point, there is a number of abstract characters that can in addition be represented using a sequence of more than one code point. For example, the abstract character “LATIN CAPITAL LETTER C WITH CEDILLA” can be represented as a single precomposed character at code position U+00C7, or as a sequence of a base character at code position U+0043 (LATIN CAPITAL LETTER C), followed by a combining character at code position U+0327 (COMBINING CEDILLA). The comparison operators on strings compare at the level of Unicode code points. This may be counter-intuitive to humans. For example, To compare strings at the level of abstract characters (that is, in a way intuitive to humans), use Due to automatic garbage-collection, free lists, and the dynamic nature of
descriptors, you may notice seemingly unusual behaviour in certain uses of the The power operator The |