Home > Mobile >  How to make python stop looking if there is a negative value?
How to make python stop looking if there is a negative value?

Time:08-11

I have a dict:

ff = {("Tom Brady",45678 ): [[456.0, 4050.0], [0.32, 5.6]]}

and

f = {("Tom Brady",45678 ): [[456.0, 4050.0, -1000.0], [0.32, 5.6, 4.56]]}

I have this code:

def find_neg (client_list: dict[tuple[str, int], list[list[float]]], client: tuple[str, int]) -> int

for a in client_list[client][0]: 
    if a>0:
      return 2
    if a<0
      return 1

the problem with this code is that when there is no negative value, python gives me an error telling me it cannot be NoneType. I want the code to give me an answer if there is a negative, but instead it only gives me an error.

CodePudding user response:

You could make the list of lists (the value in your dictionaries) into one big list, and then use list comprehension to create a new list that only holds the negative numbers. If the length of this list comprehension result is bigger than 0, then you have negative numbers in any of the lists that is in the value of your dictionary.

def find_neg (client_list: dict[tuple[str, int], list[list[float]]], client: tuple[str, int]) -> int:
    big_list = sum(client_list[client], [])
    negatives = [i for i in big_list if i < 0]
    if len(negatives) > 0:
        return True
    return False

(the sum is a little trick to create one list out of a list of lists).

As per comments; if you only need to know if there was a negative number (and you will never need to know what number(s) those were), you could simplify:

def find_neg (client_list: dict[tuple[str, int], list[list[float]]], client: tuple[str, int]) -> int:
    big_list = sum(client_list[client], [])
    for i in big_list:
        if i < 0:
            return True
    return False

CodePudding user response:

Your current logic is:

def help_find_neg(lst: list[float]):
    for element in lst: 
        if element > 0:
            return 2
        if element < 0:
            return 1
        # and if element == 0: go to the next element

If your lst consists only of zeros, the function will skip all of them (and return None).

This might be the reason behind your NoneType error.

  • Related