On 17/12/2013 14:21, 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?
You've just done that above, or have I missed something?
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")
So zero is now considered a 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?
Very strong hints, first why not try code snippets at the interactive
prompt as that's what it's for, second modify the body of the code in
your original check_values functions by removing one word.
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor