Although the two other answers follow the same reasoning as the code shown in the question and contain algorithms to count positive numbers in a list, neither of them meets the question statement.
Let’s see, in parts:
Create a Python function that receives a list
The purpose of the question is to create a function that has a parameter: a list.
The text does not ask to receive user data or to criticize if the value is numerical before calling this function, let alone receive data within of function.
And continues:
and returns how many numbers are positive
Again, the question does not ask the function to print how many numbers are positive. All it needs to do is return the counting of positive numbers.
Finally:
If a list element is not an integer or real number (float), the function must stop and return an error stating that the list can only have elements with numerical values.
In this case, it is unclear whether the "error" is an object of the type Error
or a String, but considering that the code that will call the function knows that it can return an error, it is more convenient to use the principle of encapsulation and return an object of type Error
. Also, any function Refactoring to include more information in the error return would be transparent to all lines calling this function.
Why is this important?
If this function is called from a unit test, none of the other answers will work.
But it’s not just that...
There’s a saying that says: "The computer doesn’t do what you want, it does what you say!"
Similarly, the programmer needs to understand the problem and be able to follow the given instructions.
The "gold plating", or "golden pill" in good Portuguese, is one of the causes of the failure of many software projects.
As a last thought, I suggest simplicity, citing Zen Of Python:
Simple is Better than Complex.
Readability Counts.
Based on all this, my answer is this:
def positivos(lista):
try:
positivos = [float(i) for i in lista if i > 0]
except TypeError:
raise TypeError('A lista só pode ter elementos com valores numéricos.')
return len(positivos)
This answer uses a list comprehension to reduce the original list to one with only positive numbers.
The function float(i)
ensures that the number is integer or real, or generates a Typeerror;
For each value of the list for i in lista
;
If the value is positive if i > 0
.
The return is the size of the list of positive numbers, ie the amount.
return len(positivos)
Some test entries:
print(positivos([-1, 0, 1]))
print(positivos([-1, 0]))
print(positivos([-1, 0, 'a']))
Your
lista
will always be a string, because the return of the functioninput
is that kind.– Woss
@Andersoncarloswoss to some way to change that?
– Renato Ribeiro