[Tutor] Built In Functions
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Tue Dec 17 16:42:09 CET 2013
Rafael Knuth <rafael.knuth <at> gmail.com> writes:
>
> Hej there,
>
> > I use any() and all() frequently. For example, suppose you have a
> > function that takes a list of numbers, and they are all supposed to be
> > positive.
> >
> > def calculate_values(numbers):
> > if all(number > 0 for number in numbers):
> > # do the calculation
> > else:
> > raise ValueError("negative or zero number found")
> >
> > That could be re-written as:
> >
> > def calculate_values(numbers):
> > if any(number <= 0 for number in numbers):
> > raise ValueError("negative or zero number found")
> > else:
> > # do the calculation
>
> Got it. I played with the examples above, I wrote wrote two functions
> and they work nicely.
> I understand now why it makes sense to use all() and any():
>
> def check_values(a, b):
> if all(number >= 0 for number in range(a, b)):
> return True
> else:
> raise ValueError("negative number")
>
> And:
>
> def check_values(a, b):
> if any(number >= 0 for number in range(a, b)):
> return True
> else:
> raise ValueError("negative number")
>
I wonder what you think these functions are doing exactly ?
Have you tried, e.g.,
check_values(-3, -10)
??
Also, I would say you should either return True/False for a passed/failed
check, or return None/raise an error.
The last variant simplifies your function to:
def check_values(a, b):
if any(number < 0 for number in range(a, b)):
raise ValueError("negative number")
In your example, you would never inspect the return value because the
absence of an error already tells you what the outcome was.
> But what if I have to check multiple values within one function? I am
> able to get the task done with a plain vanilla if statement. In the
> exemplary function below the user is expected to enter only positive
> numbers and in case he provides a negative number, a ValueError is
> raised:
>
> 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?
>
You can't unless you pack them into an iterable since this is what any() and
all() expect. The simplest way would be to generate the tuple (a,b), then
use that tuple like numbers in Steven's example.
BUT: this really doesn't make much sense! Your if construct is a lot more
readable than what any or all would give you in this example.
As pointed out repeatedly here, you can always replace any() and all() with
a combination of for and if, it's really a question of readability (and
style) what you choose.
Best,
Wolfgang
More information about the Tutor
mailing list