[Tutor] Built In Functions

Peter Otten __peter__ at web.de
Tue Dec 17 16:27:44 CET 2013


Rafael Knuth wrote:

> 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?

The first one could become

def positive_calulator(a, b):
    summands = a, b
    if all(x > 0 for x in summands):
        return sum(summands)
    raise ValueError("negative argument encountered")

You can make that work with and arbitrary number of arguments (and save a 
line of code):

def positive_calculator(*summands):
    if all(x > 0 for x in summands):
        return sum(summands)
    raise ValueError("negative argument encountered")



More information about the Tutor mailing list