Guido van Rossum | 46f3e00 | 1992-08-14 09:11:01 +0000 | [diff] [blame] | 1 | \chapter{Expressions and conditions} |
| 2 | \index{expression} |
| 3 | \index{condition} |
| 4 | |
| 5 | {\bf Note:} In this and the following chapters, extended BNF notation |
| 6 | will be used to describe syntax, not lexical analysis. |
| 7 | \index{BNF} |
| 8 | |
| 9 | This chapter explains the meaning of the elements of expressions and |
| 10 | conditions. Conditions are a superset of expressions, and a condition |
| 11 | may be used wherever an expression is required by enclosing it in |
| 12 | parentheses. The only places where expressions are used in the syntax |
| 13 | instead of conditions is in expression statements and on the |
| 14 | right-hand side of assignment statements; this catches some nasty bugs |
| 15 | like accidentally writing \verb\x == 1\ instead of \verb\x = 1\. |
| 16 | \indexii{assignment}{statement} |
| 17 | |
| 18 | The comma plays several roles in Python's syntax. It is usually an |
| 19 | operator with a lower precedence than all others, but occasionally |
| 20 | serves other purposes as well; e.g. it separates function arguments, |
| 21 | is used in list and dictionary constructors, and has special semantics |
| 22 | in \verb\print\ statements. |
| 23 | \index{comma} |
| 24 | |
| 25 | When (one alternative of) a syntax rule has the form |
| 26 | |
| 27 | \begin{verbatim} |
| 28 | name: othername |
| 29 | \end{verbatim} |
| 30 | |
| 31 | and no semantics are given, the semantics of this form of \verb\name\ |
| 32 | are the same as for \verb\othername\. |
| 33 | \index{syntax} |
| 34 | |
| 35 | \section{Arithmetic conversions} |
| 36 | \indexii{arithmetic}{conversion} |
| 37 | |
| 38 | When a description of an arithmetic operator below uses the phrase |
| 39 | ``the numeric arguments are converted to a common type'', |
| 40 | this both means that if either argument is not a number, a |
| 41 | \verb\TypeError\ exception is raised, and that otherwise |
| 42 | the following conversions are applied: |
| 43 | \exindex{TypeError} |
| 44 | \indexii{floating point}{number} |
| 45 | \indexii{long}{integer} |
| 46 | \indexii{plain}{integer} |
| 47 | |
| 48 | \begin{itemize} |
| 49 | \item first, if either argument is a floating point number, |
| 50 | the other is converted to floating point; |
| 51 | \item else, if either argument is a long integer, |
| 52 | the other is converted to long integer; |
| 53 | \item otherwise, both must be plain integers and no conversion |
| 54 | is necessary. |
| 55 | \end{itemize} |
| 56 | |
| 57 | \section{Atoms} |
| 58 | \index{atom} |
| 59 | |
| 60 | Atoms are the most basic elements of expressions. Forms enclosed in |
| 61 | reverse quotes or in parentheses, brackets or braces are also |
| 62 | categorized syntactically as atoms. The syntax for atoms is: |
| 63 | |
| 64 | \begin{verbatim} |
| 65 | atom: identifier | literal | enclosure |
| 66 | enclosure: parenth_form | list_display | dict_display | string_conversion |
| 67 | \end{verbatim} |
| 68 | |
| 69 | \subsection{Identifiers (Names)} |
| 70 | \index{name} |
| 71 | \index{identifier} |
| 72 | |
| 73 | An identifier occurring as an atom is a reference to a local, global |
| 74 | or built-in name binding. If a name can be assigned to anywhere in a |
| 75 | code block, and is not mentioned in a \verb\global\ statement in that |
| 76 | code block, it refers to a local name throughout that code block. |
| 77 | Otherwise, it refers to a global name if one exists, else to a |
| 78 | built-in name. |
| 79 | \indexii{name}{binding} |
| 80 | \index{code block} |
| 81 | \stindex{global} |
| 82 | \indexii{built-in}{name} |
| 83 | \indexii{global}{name} |
| 84 | |
| 85 | When the name is bound to an object, evaluation of the atom yields |
| 86 | that object. When a name is not bound, an attempt to evaluate it |
| 87 | raises a \verb\NameError\ exception. |
| 88 | \exindex{NameError} |
| 89 | |
| 90 | \subsection{Literals} |
| 91 | \index{literal} |
| 92 | |
| 93 | Python knows string and numeric literals: |
| 94 | |
| 95 | \begin{verbatim} |
| 96 | literal: stringliteral | integer | longinteger | floatnumber |
| 97 | \end{verbatim} |
| 98 | |
| 99 | Evaluation of a literal yields an object of the given type (string, |
| 100 | integer, long integer, floating point number) with the given value. |
| 101 | The value may be approximated in the case of floating point literals. |
| 102 | See section \ref{literals} for details. |
| 103 | |
| 104 | All literals correspond to immutable data types, and hence the |
| 105 | object's identity is less important than its value. Multiple |
| 106 | evaluations of literals with the same value (either the same |
| 107 | occurrence in the program text or a different occurrence) may obtain |
| 108 | the same object or a different object with the same value. |
| 109 | \indexiii{immutable}{data}{type} |
| 110 | |
| 111 | (In the original implementation, all literals in the same code block |
| 112 | with the same type and value yield the same object.) |
| 113 | |
| 114 | \subsection{Parenthesized forms} |
| 115 | \index{parenthesized form} |
| 116 | |
| 117 | A parenthesized form is an optional condition list enclosed in |
| 118 | parentheses: |
| 119 | |
| 120 | \begin{verbatim} |
| 121 | parenth_form: "(" [condition_list] ")" |
| 122 | \end{verbatim} |
| 123 | |
| 124 | A parenthesized condition list yields whatever that condition list |
| 125 | yields. |
| 126 | |
| 127 | An empty pair of parentheses yields an empty tuple object. Since |
| 128 | tuples are immutable, the rules for literals apply here. |
| 129 | \indexii{empty}{tuple} |
| 130 | |
| 131 | (Note that tuples are not formed by the parentheses, but rather by use |
| 132 | of the comma operator. The exception is the empty tuple, for which |
| 133 | parentheses {\em are} required --- allowing unparenthesized ``nothing'' |
| 134 | in expressions would causes ambiguities and allow common typos to |
| 135 | pass uncaught.) |
| 136 | \index{comma} |
| 137 | \indexii{tuple}{display} |
| 138 | |
| 139 | \subsection{List displays} |
| 140 | \indexii{list}{display} |
| 141 | |
| 142 | A list display is a possibly empty series of conditions enclosed in |
| 143 | square brackets: |
| 144 | |
| 145 | \begin{verbatim} |
| 146 | list_display: "[" [condition_list] "]" |
| 147 | \end{verbatim} |
| 148 | |
| 149 | A list display yields a new list object. |
| 150 | \obindex{list} |
| 151 | |
| 152 | If it has no condition list, the list object has no items. Otherwise, |
| 153 | the elements of the condition list are evaluated from left to right |
| 154 | and inserted in the list object in that order. |
| 155 | \indexii{empty}{list} |
| 156 | |
| 157 | \subsection{Dictionary displays} \label{dict} |
| 158 | \indexii{dictionary}{display} |
| 159 | |
| 160 | A dictionary display is a possibly empty series of key/datum pairs |
| 161 | enclosed in curly braces: |
| 162 | \index{key} |
| 163 | \index{datum} |
| 164 | \index{key/datum pair} |
| 165 | |
| 166 | \begin{verbatim} |
| 167 | dict_display: "{" [key_datum_list] "}" |
| 168 | key_datum_list: key_datum ("," key_datum)* [","] |
| 169 | key_datum: condition ":" condition |
| 170 | \end{verbatim} |
| 171 | |
| 172 | A dictionary display yields a new dictionary object. |
| 173 | \obindex{dictionary} |
| 174 | |
| 175 | The key/datum pairs are evaluated from left to right to define the |
| 176 | entries of the dictionary: each key object is used as a key into the |
| 177 | dictionary to store the corresponding datum. |
| 178 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 179 | Restrictions on the types of the key values are listed earlier in |
| 180 | section \ref{types}. |
| 181 | Clashes between duplicate keys are not detected; the last |
Guido van Rossum | 46f3e00 | 1992-08-14 09:11:01 +0000 | [diff] [blame] | 182 | datum (textually rightmost in the display) stored for a given key |
| 183 | value prevails. |
| 184 | \exindex{TypeError} |
| 185 | |
| 186 | \subsection{String conversions} |
| 187 | \indexii{string}{conversion} |
| 188 | |
| 189 | A string conversion is a condition list enclosed in reverse (or |
| 190 | backward) quotes: |
| 191 | |
| 192 | \begin{verbatim} |
| 193 | string_conversion: "`" condition_list "`" |
| 194 | \end{verbatim} |
| 195 | |
| 196 | A string conversion evaluates the contained condition list and |
| 197 | converts the resulting object into a string according to rules |
| 198 | specific to its type. |
| 199 | |
| 200 | If the object is a string, a number, \verb\None\, or a tuple, list or |
| 201 | dictionary containing only objects whose type is one of these, the |
| 202 | resulting string is a valid Python expression which can be passed to |
| 203 | the built-in function \verb\eval()\ to yield an expression with the |
| 204 | same value (or an approximation, if floating point numbers are |
| 205 | involved). |
| 206 | |
| 207 | (In particular, converting a string adds quotes around it and converts |
| 208 | ``funny'' characters to escape sequences that are safe to print.) |
| 209 | |
| 210 | It is illegal to attempt to convert recursive objects (e.g. lists or |
| 211 | dictionaries that contain a reference to themselves, directly or |
| 212 | indirectly.) |
| 213 | \obindex{recursive} |
| 214 | |
| 215 | \section{Primaries} \label{primaries} |
| 216 | \index{primary} |
| 217 | |
| 218 | Primaries represent the most tightly bound operations of the language. |
| 219 | Their syntax is: |
| 220 | |
| 221 | \begin{verbatim} |
| 222 | primary: atom | attributeref | subscription | slicing | call |
| 223 | \end{verbatim} |
| 224 | |
| 225 | \subsection{Attribute references} |
| 226 | \indexii{attribute}{reference} |
| 227 | |
| 228 | An attribute reference is a primary followed by a period and a name: |
| 229 | |
| 230 | \begin{verbatim} |
| 231 | attributeref: primary "." identifier |
| 232 | \end{verbatim} |
| 233 | |
| 234 | The primary must evaluate to an object of a type that supports |
| 235 | attribute references, e.g. a module or a list. This object is then |
| 236 | asked to produce the attribute whose name is the identifier. If this |
| 237 | attribute is not available, the exception \verb\AttributeError\ is |
| 238 | raised. Otherwise, the type and value of the object produced is |
| 239 | determined by the object. Multiple evaluations of the same attribute |
| 240 | reference may yield different objects. |
| 241 | \obindex{module} |
| 242 | \obindex{list} |
| 243 | |
| 244 | \subsection{Subscriptions} |
| 245 | \index{subscription} |
| 246 | |
| 247 | A subscription selects an item of a sequence (string, tuple or list) |
| 248 | or mapping (dictionary) object: |
| 249 | \obindex{sequence} |
| 250 | \obindex{mapping} |
| 251 | \obindex{string} |
| 252 | \obindex{tuple} |
| 253 | \obindex{list} |
| 254 | \obindex{dictionary} |
| 255 | \indexii{sequence}{item} |
| 256 | |
| 257 | \begin{verbatim} |
| 258 | subscription: primary "[" condition "]" |
| 259 | \end{verbatim} |
| 260 | |
| 261 | The primary must evaluate to an object of a sequence or mapping type. |
| 262 | |
| 263 | If it is a mapping, the condition must evaluate to an object whose |
| 264 | value is one of the keys of the mapping, and the subscription selects |
| 265 | the value in the mapping that corresponds to that key. |
| 266 | |
| 267 | If it is a sequence, the condition must evaluate to a plain integer. |
| 268 | If this value is negative, the length of the sequence is added to it |
| 269 | (so that, e.g. \verb\x[-1]\ selects the last item of \verb\x\.) |
| 270 | The resulting value must be a nonnegative integer smaller than the |
| 271 | number of items in the sequence, and the subscription selects the item |
| 272 | whose index is that value (counting from zero). |
| 273 | |
| 274 | A string's items are characters. A character is not a separate data |
| 275 | type but a string of exactly one character. |
| 276 | \index{character} |
| 277 | \indexii{string}{item} |
| 278 | |
| 279 | \subsection{Slicings} |
| 280 | \index{slicing} |
| 281 | \index{slice} |
| 282 | |
| 283 | A slicing (or slice) selects a range of items in a sequence (string, |
| 284 | tuple or list) object: |
| 285 | \obindex{sequence} |
| 286 | \obindex{string} |
| 287 | \obindex{tuple} |
| 288 | \obindex{list} |
| 289 | |
| 290 | \begin{verbatim} |
| 291 | slicing: primary "[" [condition] ":" [condition] "]" |
| 292 | \end{verbatim} |
| 293 | |
| 294 | The primary must evaluate to a sequence object. The lower and upper |
| 295 | bound expressions, if present, must evaluate to plain integers; |
| 296 | defaults are zero and the sequence's length, respectively. If either |
| 297 | bound is negative, the sequence's length is added to it. The slicing |
| 298 | now selects all items with index $k$ such that $i <= k < j$ where $i$ |
| 299 | and $j$ are the specified lower and upper bounds. This may be an |
| 300 | empty sequence. It is not an error if $i$ or $j$ lie outside the |
| 301 | range of valid indexes (such items don't exist so they aren't |
| 302 | selected). |
| 303 | |
| 304 | \subsection{Calls} \label{calls} |
| 305 | \index{call} |
| 306 | |
| 307 | A call calls a callable object (e.g. a function) with a possibly empty |
| 308 | series of arguments: |
| 309 | \obindex{callable} |
| 310 | |
| 311 | \begin{verbatim} |
| 312 | call: primary "(" [condition_list] ")" |
| 313 | \end{verbatim} |
| 314 | |
| 315 | The primary must evaluate to a callable object (user-defined |
| 316 | functions, built-in functions, methods of built-in objects, class |
| 317 | objects, and methods of class instances are callable). If it is a |
| 318 | class, the argument list must be empty; otherwise, the arguments are |
| 319 | evaluated. |
| 320 | |
| 321 | A call always returns some value, possibly \verb\None\, unless it |
| 322 | raises an exception. How this value is computed depends on the type |
| 323 | of the callable object. If it is: |
| 324 | |
| 325 | \begin{description} |
| 326 | |
| 327 | \item[a user-defined function:] the code block for the function is |
| 328 | executed, passing it the argument list. The first thing the code |
| 329 | block will do is bind the formal parameters to the arguments; this is |
| 330 | described in section \ref{function}. When the code block executes a |
| 331 | \verb\return\ statement, this specifies the return value of the |
| 332 | function call. |
| 333 | \indexii{function}{call} |
| 334 | \indexiii{user-defined}{function}{call} |
| 335 | \obindex{user-defined function} |
| 336 | \obindex{function} |
| 337 | |
| 338 | \item[a built-in function or method:] the result is up to the |
| 339 | interpreter; see the library reference manual for the descriptions of |
| 340 | built-in functions and methods. |
| 341 | \indexii{function}{call} |
| 342 | \indexii{built-in function}{call} |
| 343 | \indexii{method}{call} |
| 344 | \indexii{built-in method}{call} |
| 345 | \obindex{built-in method} |
| 346 | \obindex{built-in function} |
| 347 | \obindex{method} |
| 348 | \obindex{function} |
| 349 | |
| 350 | \item[a class object:] a new instance of that class is returned. |
| 351 | \obindex{class} |
| 352 | \indexii{class object}{call} |
| 353 | |
| 354 | \item[a class instance method:] the corresponding user-defined |
| 355 | function is called, with an argument list that is one longer than the |
| 356 | argument list of the call: the instance becomes the first argument. |
| 357 | \obindex{class instance} |
| 358 | \obindex{instance} |
| 359 | \indexii{instance}{call} |
| 360 | \indexii{class instance}{call} |
| 361 | |
| 362 | \end{description} |
| 363 | |
| 364 | \section{Unary arithmetic operations} |
| 365 | \indexiii{unary}{arithmetic}{operation} |
| 366 | \indexiii{unary}{bit-wise}{operation} |
| 367 | |
| 368 | All unary arithmetic (and bit-wise) operations have the same priority: |
| 369 | |
| 370 | \begin{verbatim} |
| 371 | u_expr: primary | "-" u_expr | "+" u_expr | "~" u_expr |
| 372 | \end{verbatim} |
| 373 | |
| 374 | The unary \verb\"-"\ (minus) operator yields the negation of its |
| 375 | numeric argument. |
| 376 | \index{negation} |
| 377 | \index{minus} |
| 378 | |
| 379 | The unary \verb\"+"\ (plus) operator yields its numeric argument |
| 380 | unchanged. |
| 381 | \index{plus} |
| 382 | |
| 383 | The unary \verb\"~"\ (invert) operator yields the bit-wise inversion |
| 384 | of its plain or long integer argument. The bit-wise inversion of |
| 385 | \verb\x\ is defined as \verb\-(x+1)\. |
| 386 | \index{inversion} |
| 387 | |
| 388 | In all three cases, if the argument does not have the proper type, |
| 389 | a \verb\TypeError\ exception is raised. |
| 390 | \exindex{TypeError} |
| 391 | |
| 392 | \section{Binary arithmetic operations} |
| 393 | \indexiii{binary}{arithmetic}{operation} |
| 394 | |
| 395 | The binary arithmetic operations have the conventional priority |
| 396 | levels. Note that some of these operations also apply to certain |
| 397 | non-numeric types. There is no ``power'' operator, so there are only |
| 398 | two levels, one for multiplicative operators and one for additive |
| 399 | operators: |
| 400 | |
| 401 | \begin{verbatim} |
| 402 | m_expr: u_expr | m_expr "*" u_expr |
| 403 | | m_expr "/" u_expr | m_expr "%" u_expr |
| 404 | a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr |
| 405 | \end{verbatim} |
| 406 | |
| 407 | The \verb\"*"\ (multiplication) operator yields the product of its |
| 408 | arguments. The arguments must either both be numbers, or one argument |
| 409 | must be a plain integer and the other must be a sequence. In the |
| 410 | former case, the numbers are converted to a common type and then |
| 411 | multiplied together. In the latter case, sequence repetition is |
| 412 | performed; a negative repetition factor yields an empty sequence. |
| 413 | \index{multiplication} |
| 414 | |
| 415 | The \verb\"/"\ (division) operator yields the quotient of its |
| 416 | arguments. The numeric arguments are first converted to a common |
| 417 | type. Plain or long integer division yields an integer of the same |
| 418 | type; the result is that of mathematical division with the `floor' |
| 419 | function applied to the result. Division by zero raises the |
| 420 | \verb\ZeroDivisionError\ exception. |
| 421 | \exindex{ZeroDivisionError} |
| 422 | \index{division} |
| 423 | |
| 424 | The \verb\"%"\ (modulo) operator yields the remainder from the |
| 425 | division of the first argument by the second. The numeric arguments |
| 426 | are first converted to a common type. A zero right argument raises |
| 427 | the \verb\ZeroDivisionError\ exception. The arguments may be floating |
| 428 | point numbers, e.g. \verb\3.14 % 0.7\ equals \verb\0.34\. The modulo |
| 429 | operator always yields a result with the same sign as its second |
| 430 | operand (or zero); the absolute value of the result is strictly |
| 431 | smaller than the second operand. |
| 432 | \index{modulo} |
| 433 | |
| 434 | The integer division and modulo operators are connected by the |
| 435 | following identity: \verb\x == (x/y)*y + (x%y)\. Integer division and |
| 436 | modulo are also connected with the built-in function \verb\divmod()\: |
| 437 | \verb\divmod(x, y) == (x/y, x%y)\. These identities don't hold for |
| 438 | floating point numbers; there a similar identity holds where |
| 439 | \verb\x/y\ is replaced by \verb\floor(x/y)\). |
| 440 | |
| 441 | The \verb\"+"\ (addition) operator yields the sum of its arguments. |
| 442 | The arguments must either both be numbers, or both sequences of the |
| 443 | same type. In the former case, the numbers are converted to a common |
| 444 | type and then added together. In the latter case, the sequences are |
| 445 | concatenated. |
| 446 | \index{addition} |
| 447 | |
| 448 | The \verb\"-"\ (subtraction) operator yields the difference of its |
| 449 | arguments. The numeric arguments are first converted to a common |
| 450 | type. |
| 451 | \index{subtraction} |
| 452 | |
| 453 | \section{Shifting operations} |
| 454 | \indexii{shifting}{operation} |
| 455 | |
| 456 | The shifting operations have lower priority than the arithmetic |
| 457 | operations: |
| 458 | |
| 459 | \begin{verbatim} |
| 460 | shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr |
| 461 | \end{verbatim} |
| 462 | |
| 463 | These operators accept plain or long integers as arguments. The |
| 464 | arguments are converted to a common type. They shift the first |
| 465 | argument to the left or right by the number of bits given by the |
| 466 | second argument. |
| 467 | |
| 468 | A right shift by $n$ bits is defined as division by $2^n$. A left |
| 469 | shift by $n$ bits is defined as multiplication with $2^n$; for plain |
| 470 | integers there is no overflow check so this drops bits and flip the |
| 471 | sign if the result is not less than $2^{31}$ in absolute value. |
| 472 | |
| 473 | Negative shift counts raise a \verb\ValueError\ exception. |
| 474 | \exindex{ValueError} |
| 475 | |
| 476 | \section{Binary bit-wise operations} |
| 477 | \indexiii{binary}{bit-wise}{operation} |
| 478 | |
| 479 | Each of the three bitwise operations has a different priority level: |
| 480 | |
| 481 | \begin{verbatim} |
| 482 | and_expr: shift_expr | and_expr "&" shift_expr |
| 483 | xor_expr: and_expr | xor_expr "^" and_expr |
| 484 | or_expr: xor_expr | or_expr "|" xor_expr |
| 485 | \end{verbatim} |
| 486 | |
| 487 | The \verb\"&"\ operator yields the bitwise AND of its arguments, which |
| 488 | must be plain or long integers. The arguments are converted to a |
| 489 | common type. |
| 490 | \indexii{bit-wise}{and} |
| 491 | |
| 492 | The \verb\"^"\ operator yields the bitwise XOR (exclusive OR) of its |
| 493 | arguments, which must be plain or long integers. The arguments are |
| 494 | converted to a common type. |
| 495 | \indexii{bit-wise}{xor} |
| 496 | \indexii{exclusive}{or} |
| 497 | |
| 498 | The \verb\"|"\ operator yields the bitwise (inclusive) OR of its |
| 499 | arguments, which must be plain or long integers. The arguments are |
| 500 | converted to a common type. |
| 501 | \indexii{bit-wise}{or} |
| 502 | \indexii{inclusive}{or} |
| 503 | |
| 504 | \section{Comparisons} |
| 505 | \index{comparison} |
| 506 | |
| 507 | Contrary to C, all comparison operations in Python have the same |
| 508 | priority, which is lower than that of any arithmetic, shifting or |
| 509 | bitwise operation. Also contrary to C, expressions like |
| 510 | \verb\a < b < c\ have the interpretation that is conventional in |
| 511 | mathematics: |
| 512 | \index{C} |
| 513 | |
| 514 | \begin{verbatim} |
| 515 | comparison: or_expr (comp_operator or_expr)* |
| 516 | comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in" |
| 517 | \end{verbatim} |
| 518 | |
| 519 | Comparisons yield integer values: 1 for true, 0 for false. |
| 520 | |
| 521 | Comparisons can be chained arbitrarily, e.g. $x < y <= z$ is |
| 522 | equivalent to $x < y$ \verb\and\ $y <= z$, except that $y$ is |
| 523 | evaluated only once (but in both cases $z$ is not evaluated at all |
| 524 | when $x < y$ is found to be false). |
| 525 | \indexii{chaining}{comparisons} |
| 526 | |
Guido van Rossum | 4ac605e | 1992-12-17 15:31:02 +0000 | [diff] [blame] | 527 | \catcode`\_=8 |
Guido van Rossum | 46f3e00 | 1992-08-14 09:11:01 +0000 | [diff] [blame] | 528 | Formally, $e_0 op_1 e_1 op_2 e_2 ...e_{n-1} op_n e_n$ is equivalent to |
| 529 | $e_0 op_1 e_1$ \verb\and\ $e_1 op_2 e_2$ \verb\and\ ... \verb\and\ |
| 530 | $e_{n-1} op_n e_n$, except that each expression is evaluated at most once. |
| 531 | |
| 532 | Note that $e_0 op_1 e_1 op_2 e_2$ does not imply any kind of comparison |
| 533 | between $e_0$ and $e_2$, e.g. $x < y > z$ is perfectly legal. |
Guido van Rossum | 4ac605e | 1992-12-17 15:31:02 +0000 | [diff] [blame] | 534 | \catcode`\_=12 |
Guido van Rossum | 46f3e00 | 1992-08-14 09:11:01 +0000 | [diff] [blame] | 535 | |
| 536 | The forms \verb\<>\ and \verb\!=\ are equivalent; for consistency with |
| 537 | C, \verb\!=\ is preferred; where \verb\!=\ is mentioned below |
| 538 | \verb\<>\ is also implied. |
| 539 | |
| 540 | The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare |
| 541 | the values of two objects. The objects needn't have the same type. |
| 542 | If both are numbers, they are coverted to a common type. Otherwise, |
| 543 | objects of different types {\em always} compare unequal, and are |
| 544 | ordered consistently but arbitrarily. |
| 545 | |
| 546 | (This unusual definition of comparison is done to simplify the |
| 547 | definition of operations like sorting and the \verb\in\ and \verb\not |
| 548 | in\ operators.) |
| 549 | |
| 550 | Comparison of objects of the same type depends on the type: |
| 551 | |
| 552 | \begin{itemize} |
| 553 | |
| 554 | \item |
| 555 | Numbers are compared arithmetically. |
| 556 | |
| 557 | \item |
| 558 | Strings are compared lexicographically using the numeric equivalents |
| 559 | (the result of the built-in function \verb\ord\) of their characters. |
| 560 | |
| 561 | \item |
| 562 | Tuples and lists are compared lexicographically using comparison of |
| 563 | corresponding items. |
| 564 | |
| 565 | \item |
| 566 | Mappings (dictionaries) are compared through lexicographic |
| 567 | comparison of their sorted (key, value) lists.% |
| 568 | \footnote{This is expensive since it requires sorting the keys first, |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 569 | but about the only sensible definition. An earlier version of Python |
| 570 | compared dictionaries by identity only, but this caused surprises |
| 571 | because people expected to be able to test a dictionary for emptiness |
| 572 | by comparing it to {\tt \{\}}.} |
Guido van Rossum | 46f3e00 | 1992-08-14 09:11:01 +0000 | [diff] [blame] | 573 | |
| 574 | \item |
| 575 | Most other types compare unequal unless they are the same object; |
| 576 | the choice whether one object is considered smaller or larger than |
| 577 | another one is made arbitrarily but consistently within one |
| 578 | execution of a program. |
| 579 | |
| 580 | \end{itemize} |
| 581 | |
| 582 | The operators \verb\in\ and \verb\not in\ test for sequence |
| 583 | membership: if $y$ is a sequence, $x ~\verb\in\~ y$ is true if and |
| 584 | only if there exists an index $i$ such that $x = y[i]$. |
| 585 | $x ~\verb\not in\~ y$ yields the inverse truth value. The exception |
| 586 | \verb\TypeError\ is raised when $y$ is not a sequence, or when $y$ is |
| 587 | a string and $x$ is not a string of length one.% |
| 588 | \footnote{The latter restriction is sometimes a nuisance.} |
| 589 | \opindex{in} |
| 590 | \opindex{not in} |
| 591 | \indexii{membership}{test} |
| 592 | \obindex{sequence} |
| 593 | |
| 594 | The operators \verb\is\ and \verb\is not\ test for object identity: |
| 595 | $x ~\verb\is\~ y$ is true if and only if $x$ and $y$ are the same |
| 596 | object. $x ~\verb\is not\~ y$ yields the inverse truth value. |
| 597 | \opindex{is} |
| 598 | \opindex{is not} |
| 599 | \indexii{identity}{test} |
| 600 | |
| 601 | \section{Boolean operations} \label{Booleans} |
| 602 | \indexii{Boolean}{operation} |
| 603 | |
| 604 | Boolean operations have the lowest priority of all Python operations: |
| 605 | |
| 606 | \begin{verbatim} |
| 607 | condition: or_test |
| 608 | or_test: and_test | or_test "or" and_test |
| 609 | and_test: not_test | and_test "and" not_test |
| 610 | not_test: comparison | "not" not_test |
| 611 | \end{verbatim} |
| 612 | |
| 613 | In the context of Boolean operations, and also when conditions are |
| 614 | used by control flow statements, the following values are interpreted |
| 615 | as false: \verb\None\, numeric zero of all types, empty sequences |
| 616 | (strings, tuples and lists), and empty mappings (dictionaries). All |
| 617 | other values are interpreted as true. |
| 618 | |
| 619 | The operator \verb\not\ yields 1 if its argument is false, 0 otherwise. |
| 620 | \opindex{not} |
| 621 | |
| 622 | The condition $x ~\verb\and\~ y$ first evaluates $x$; if $x$ is false, |
| 623 | its value is returned; otherwise, $y$ is evaluated and the resulting |
| 624 | value is returned. |
| 625 | \opindex{and} |
| 626 | |
| 627 | The condition $x ~\verb\or\~ y$ first evaluates $x$; if $x$ is true, |
| 628 | its value is returned; otherwise, $y$ is evaluated and the resulting |
| 629 | value is returned. |
| 630 | \opindex{or} |
| 631 | |
| 632 | (Note that \verb\and\ and \verb\or\ do not restrict the value and type |
| 633 | they return to 0 and 1, but rather return the last evaluated argument. |
| 634 | This is sometimes useful, e.g. if \verb\s\ is a string that should be |
| 635 | replaced by a default value if it is empty, the expression |
| 636 | \verb\s or 'foo'\ yields the desired value. Because \verb\not\ has to |
| 637 | invent a value anyway, it does not bother to return a value of the |
| 638 | same type as its argument, so e.g. \verb\not 'foo'\ yields \verb\0\, |
| 639 | not \verb\''\.) |
| 640 | |
| 641 | \section{Expression lists and condition lists} |
| 642 | \indexii{expression}{list} |
| 643 | \indexii{condition}{list} |
| 644 | |
| 645 | \begin{verbatim} |
| 646 | expr_list: or_expr ("," or_expr)* [","] |
| 647 | cond_list: condition ("," condition)* [","] |
| 648 | \end{verbatim} |
| 649 | |
| 650 | The only difference between expression lists and condition lists is |
| 651 | the lowest priority of operators that can be used in them without |
| 652 | being enclosed in parentheses; condition lists allow all operators, |
| 653 | while expression lists don't allow comparisons and Boolean operators |
| 654 | (they do allow bitwise and shift operators though). |
| 655 | |
| 656 | Expression lists are used in expression statements and assignments; |
| 657 | condition lists are used everywhere else where a list of |
| 658 | comma-separated values is required. |
| 659 | |
| 660 | An expression (condition) list containing at least one comma yields a |
| 661 | tuple. The length of the tuple is the number of expressions |
| 662 | (conditions) in the list. The expressions (conditions) are evaluated |
| 663 | from left to right. (Conditions lists are used syntactically is a few |
| 664 | places where no tuple is constructed but a list of values is needed |
| 665 | nevertheless.) |
| 666 | \obindex{tuple} |
| 667 | |
| 668 | The trailing comma is required only to create a single tuple (a.k.a. a |
| 669 | {\em singleton}); it is optional in all other cases. A single |
| 670 | expression (condition) without a trailing comma doesn't create a |
| 671 | tuple, but rather yields the value of that expression (condition). |
| 672 | \indexii{trailing}{comma} |
| 673 | |
| 674 | (To create an empty tuple, use an empty pair of parentheses: |
| 675 | \verb\()\.) |