[Tutor] Built In Functions
Steven D'Aprano
steve at pearwood.info
Tue Dec 17 16:39:43 CET 2013
On Tue, Dec 17, 2013 at 03:21:34PM +0100, Rafael Knuth wrote:
> def PositiveCalculator(a, b):
> if a > 0 and b > 0:
> return a + b
> else:
> raise ValueError("negative number")
>
> In this function one negative number is tolerated:
>
> def PositiveCalculator(a, b):
> if a > 0 or b > 0:
> return a + b
> else:
> raise ValueError("negative number")
>
> How would I have to modify these two functions if I wanted to use the
> all( ) or any() function respectively?
I wouldn't do that. The above is perfectly readable and efficient,
putting them into any/all just makes more work for the reader and for
the computer.
But if you must, the trick is to remember that a tuple (a, b) is a
sequence that can be looped over too, so:
if all(x > 0 for x in (a, b)):
if any(x > 0 for x in (a, b)):
But as I said, I wouldn't do that for just two variables. Maybe for
three, or four.
if a > 0 and b > 0 and c > 0:
if all(x for x in (a, b, c):
--
Steven
More information about the Tutor
mailing list