I am making a function that should return True
if the elements of my list are positive numbers and False
if there is at least one negative number. However, I have a problem when I want to print a message if the boolean value is False
. How could I modify it, so that it returns the message: You have negative numbers in your list ? My code is the following:
lista_numeros = [500,60,89,-20,56,36]
def todos_positivos(lista):
for i in lista:
if i < 0:
return False and print("Tienes números negativos en tu lista")
else:
pass
return True and print("Todos los números son positivos")
resultado = todos_positivos(lista_numeros)
print(resultado)
When I put positive numbers in my defined list, it does return the message after the result, True
but not when there is a negative number.
Good day,
Print the text before using
return
.Another thing that can be improved about your code is that you don't need the
else
if any number is negative it will print "You have negative numbers in your list" and returnFalse
interrupting the loopfor
. If the cycle ends without being interrupted, it means that all the numbers are positive.Example:
Performance example:
Edit: Another option could be to use
any()
with a generator.Edit 2: If you only have to return
True
orFalse
you could make it more compact