[Tutor] using 'and ' and 'or' with integers
Mitya Sirenef
msirenef at lightbird.net
Wed Jan 9 08:41:03 CET 2013
On Wed 09 Jan 2013 01:56:20 AM EST, ken brockman wrote:
> I was looking through some lab material from a computer course offered
> at UC Berkeley and came across some examples in the form of questions
> on a test about python.
> 1 and 2 and 3
> answer 3
> I've goggled it till i was red in the fingers, but to no avail.. Could
> someone be kind enuff to direct me to some docs that explain this??
> I've no clue what the hell is going on here..
> Thanks much for any help you may supply.
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
It returns last evaluated value. If you have '1 and 2', 1
is 'truthy', so it needs to evaluate 2, and then 2 is returned.
With '0 and 2', 0 is falsy, so it does not need to evaluate
past it and returns 0.
With '0 or 2', it needs to evaluate 2 and returns its value.
This is particularly useful to assign only when a value is
falsy:
default_x = 5
def f(x):
x = x or default_x
So if x is provided, it is used, but if x is, let's say, None,
default_x will be used.
HTH, - mitya
--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
More information about the Tutor
mailing list