Python
  Home arrow Python arrow Python Expressions and Operators
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

Python Expressions and Operators
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2008-10-02

    Table of Contents:
  • Python Expressions and Operators
  • The Python 2.5 ternary operator
  • Arithmetic Operations
  • Sequence Operations

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Python Expressions and Operators


    (Page 1 of 4 )

    In this fourth part of a nine-part series on Python, you'll learn about expressions, operators, sequences, and more. This article is excerpted from chapter four of the book Python in a Nutshell, Second Edition, written by Alex Martelli (O'Reilly; ISBN: 0596100469). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

    Expressions and Operators

    An expression is a phrase of code that Python evaluates to produce a value. The simplest expressions are literals and identifiers. You build other expressions by joining subexpressions with the operators and/or delimiters in Table 4-2. This table lists operators in decreasing order of precedence, higher precedence before lower. Operators listed together have the same precedence. The third column lists the associativity of the operator: L (left-to-right), R (right-to-left), or NA (nonassociative).

    Table 4-2. Operator precedence in expressions

    Operator Description Associativity
    `expr,...` String conversion NA
    {key:expr,...} Dictionary creation NA
    [expr,...] List creation NA
    (expr,...) Tuple creation or just parentheses NA
    f(expr,...) Function call L
    x[index:index] Slicing L
    x[index] Indexing L
    x.att r Attribute reference L
    x**y Exponentiation ( x to y th power) R
    ~x Bitwise NOT NA
    +x , -x Unary plus and minus NA
    x*y , x/y , x//y , x%y Multiplication, division, truncating division, remainder L
    x+y , x-y Addition, subtraction L
    x<<y , x>>y Left-shift, right-shift L
    x&y Bitwise AND L
    x^y Bitwise XOR L
    x|y Bitwise OR L
    x<y , x<=y , x>y , xy , x<<>>y , Comparisons (less than, less than or NA
    x!=y , x==y equal, greater than, greater than or equal, inequality, equality) a  
    x is y , x is not y Identity tests NA
    x in y , x not in y Membership tests NA
    not x Boolean NOT NA
    x and y Boolean AND L
    x or y Boolean OR L
    lambda arg,...: expr Anonymous simple function NA

    a <> and != are alternate forms of the same operator. != is the preferred version; <> is obsolete.

    In Table 4-2, exprkey ,  findexx , and y indicate any expression, while attr and arg  indicate any identifier. The notation ,... means commas join zero or more repetitions, except for string conversion, where you need one or more repetitions.

    A trailing comma is allowed and innocuous in all such cases, except for string conversion, where it's forbidden. The string conversion operator, with its quirky behavior, is not recommended; use built-in function repr (covered in repr on page 166) instead.

    Comparison Chaining

    You can chain comparisons, implying a logical and. For example:

      a < b <= c < d

    has the same meaning as:

      a < b and b <= c and c < d

    The chained form is more readable and evaluates each subexpression once at the most.

    Short-Circuiting Operators

    Operators and and or short-circuit their operands' evaluation: the righthand operand evaluates only if its value is needed to get the truth value of the entire and or or operation.

    In other words, x  and y  first evaluates x. If x  is false, the result is x ; otherwise, the result is y. Similarly, x or y first evaluates x. If x  is true, the result is x ; otherwise, the result is y .

    and and or don't force their results to be True or False, but rather return one or the other of their operands. This lets you use these operators more generally, not just in Boolean contexts. and and or, because of their short-circuiting semantics, differ from all other operators, which fully evaluate all operands before performing the operation. and and or let the left operand act as a guard for the right operand.

    More Python Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Python in a Nutshell, Second Edition,"...
     

    Buy this book now. This article is excerpted from chapter four of the book Python in a Nutshell, Second Edition, written by Alex Martelli (O'Reilly; ISBN: 0596100469). Check it out today at your favorite bookstore. Buy this book now.

       

    PYTHON ARTICLES

    - Nested Functions in Python
    - Python Parameters, Functions and Arguments
    - Python Statements and Functions
    - Statements and Iterators in Python
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT