[Tutor] Better way to compare values?

memilanuk memilanuk at gmail.com
Mon Aug 29 05:33:29 CEST 2011

> There's a few things that can make this a lot shorter. To address your
> primary question first, the python idiom for this is like so:
> if 10 in (a, b):
> it constructs a tuple containing the variables a and b, then checks if
> the number ten is inside that tuple. simple and straightforward. Now,
> or's aren't limited to just two operands. you can chain multiple or's
> together to make this function even shorter, like so:
> if a == 10 or b == 10 or a + b == 10:

That's pretty much what the 'book' solution was (found the 'Show 
Solution' button staring me in the face shortly after posting my 
question here.

def makes10(a,b)
	return(a == 10 or b == 10 or a + b == 10)

> So, all said and done, the solution to your problem in idiomatic
> python looks like this:
> def makes10(a, b):
>      return 10 in (a, b, a + b)

Something else I learned from this... for some reason I had the idea in 
my head that 'return' was a function like print() i.e. 'return()'. 
Obviously not, from your example and from others that I dug up in the 
Python docs.

Thanks for the detailed explanation - it was very clear and easy to 
follow!  What I had originally been thinking was something like 'a && b' 
or 'a || b'... but that was probably some cross-pollenation from earlier 
dabbling in PHP or something ;)



More information about the Tutor mailing list