Re: 1 or 1/0 doesn't raise an exception

Discussion in 'Python' started by Tim Chase, Dec 14, 2008.

  1. Tim Chase

    Tim Chase Guest

    > Is it a feature that
    >
    > 1 or 1/0
    >
    > returns 1 and doesn't raise a ZeroDivisionError? If so, what's the rationale?


    Yes, it's a feature:

    http://en.wikipedia.org/wiki/Short-circuit_evaluation

    When you have "True or False", you know it's true by the time
    you've got the first piece, so there's no need to evaluate the
    2nd piece. The opposite is helpful too:

    lst = [some list or an empty list]
    ...
    if lst and lst[0] == 42:

    This ensures that the "lst[0]" doesn't fail if lst is empty,
    because lst evaluating to false (an empty list) short-circuits
    preventing the evaluation of "lst[0]".

    -tkc
     
    Tim Chase, Dec 14, 2008
    #1
    1. Advertising

  2. Tim Chase

    r Guest

    These are just the kind of things that make Python so beautiful ;)
    Thanks Guido!
     
    r, Dec 14, 2008
    #2
    1. Advertising

  3. Tim Chase

    News123 Guest

    Hi.

    r wrote:
    > These are just the kind of things that make Python so beautiful ;)
    > Thanks Guido!



    You shouldn't forget to thank K&R ;-)
    Shortcutting logical operation shortcuts existed already in C and has
    been adopted by quite a lot of programming languages.


    bye


    N
     
    News123, Dec 14, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Bengt Richter
    Replies:
    0
    Views:
    374
    Bengt Richter
    Jul 7, 2005
  2. Jacol

    raise or not to raise [Newbie]

    Jacol, Feb 3, 2007, in forum: Python
    Replies:
    5
    Views:
    425
    Gabriel Genellina
    Feb 5, 2007
  3. ernest
    Replies:
    2
    Views:
    301
    Roy Smith
    Nov 14, 2010
  4. Jack Bates
    Replies:
    0
    Views:
    289
    Jack Bates
    May 2, 2011
  5. bvdp

    Raise X or Raise X()?

    bvdp, Mar 11, 2012, in forum: Python
    Replies:
    10
    Views:
    395
    Stefan Behnel
    Mar 12, 2012
Loading...

Share This Page