[Tutor] 'or' in assignment (not if statement)?

Alan Gauld alan.gauld at btinternet.com
Fri Dec 10 18:12:31 CET 2010


"Steven D'Aprano" <steve at pearwood.info> wrote

>> Python knows that if val is true then it doesn't need to evaluate 
>> the second term that causes it to return val rather than 1.
>
> That's what makes it short circuiting, but that's not why it returns 
> the first argument. `or` in standard Pascal doesn't short-circuit.

But Pascal returns a boolean result, it doesn't return the original
value of either term, it returns the true Boolean value of the
expression.

> Take this example `or.p` file:

I don't see what point you are trying to make?
Other than that Pascal doesn't do short-circuit evaluation.
But that doesn't relate to the fact that its a combination
of Python doing short circuit evaluation plus returning the
original value that enables the "val or 1" idiom to work.

>> It's a boolean expression you would reasonably expect a true 
>> boolean result.
>
> That brought a smile to my face! That's very amusing, the idea that 
> *boolean algebra* is intuitively expected!

It is if you are used to computer programming languages :-)
So for example if I do

print len("foo")
I don't expect "bar" - even though bar does have
the same length as "foo".

The way most languages nowadays treat logic is inconsistent
with how they treat other operations but done for the many
conveniences that such an approach has over the more purist.
eg
if myString

rather than

if myString == ""

etc.

> As an experiment, offer to buy your wife dinner, and ask if she'd 
> prefer to go to an Italian or Chinese restaurant.

:-)
She would either answer "Yes" (she would like to go to one of
them, and if I'm lucky she might give me a clue which!) or "No"
(she would prefer neither, Indian perhaps...)

> If she says that she doesn't understand the question, because 
> restaurants aren't True/False boolean values, then you might have a 
> point :)

Yes, I agree that only a truue mathematician would reply like that.

Alan G.




More information about the Tutor mailing list