[Tutor] Built In Functions
Rafael Knuth
rafael.knuth at gmail.com
Tue Dec 17 15:21:34 CET 2013
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")
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?
Thanks in advance!
All the best,
Raf
More information about the Tutor
mailing list