Home > Enterprise >  Does not execute if and elif statement in a recursive function that appends
Does not execute if and elif statement in a recursive function that appends

Time:02-03

I don't understand why the if and elif statement with the append in it is not executed. I converted the hht and hat variable in so it can be compared.

a = {0: {'halbzeit_h_tore': '1', 'halbzeit_a_tore': '1'}, 
     1: {'halbzeit_h_tore': '0', 'halbzeit_a_tore': '0'}, 
     2: {'halbzeit_h_tore': '1', 'halbzeit_a_tore': '0'}, 
     3: {}
    }

 
played_games_of_the_day =[]

def check_1(**kwargs):
    hht = kwargs['halbzeit_h_tore']
    hat = kwargs["halbzeit_a_tore"]
    c = 0
    if hht == "-" and hat == "-":
        played_games_of_the_day.append(0)
        c  = 1
        check_1(a[c])
    elif int(hht) == int and int(hat) == int :
        c  = 1
        played_games_of_the_day.append(1)
        check_1(a[c])
    #if dict empty pass#
    elif not bool(a[c]):
        pass
    
    if all(x==0 for x in played_games_of_the_day):
            print("all zero")
    elif all(x==1 for x in played_games_of_the_day):
            print("all one")

check_1(**a[0])
print(played_games_of_the_day)

CodePudding user response:

Never enter the if if hht == "-" and hat == "-": cause as you can see in your dictionary there is not value like that in it, and it never enters this elif elif int(hht) == int and int(hat) == int : cause your are comparing an integer with a type of variable, and that will always return False

CodePudding user response:

To properly handle the values we need to consider the scenarios.

First, in the given code the values in the dictionary are str types. In general you can check the type of the variable with isinstance function. Let's start with some examples:

my_dict = {'str_type': '1', 'int_type': 1, 'bad_str_type': 'I am not a number'}

def get_int_value(my_input):
    if isinstance(my_input, int):
        # It is already an integer
        return my_input
    elif isinstance(my_input, str):
        # Needs to be converted
        return int(my_input) # Crashes for bad strings

get_int_value(my_dict['str_type']) # returns int 1
get_int_value(my_dict['int_type']) # returns int 1
get_int_value(my_dict['bad_str_type']) # Raises ValueError

So how can we handle the crash. We can check the input value before we try to make a number (Look Before You Leap, LBYL) or detect when it fails and recover from it (Easier to Ask Forgiveness than Permission, EAFP). The choice is up to the preference of the developer.

One way to check the string for a number is to use my_input.isnumeric(). There are other options such as Regular Expressions for more complicated requirements but I digress as it's too much for this scenario.

Using LBYL:

def get_int_value(my_input):
    if isinstance(my_input, int):
        # It is already an integer
        return my_input
    elif isinstance(my_input, str):
        # Needs to be converted
        # Negative numbers start with a '-'. isnumeric does not like it
        if (my_input.startswith('-') and my_input[1:].isnumeric())
            or my_input.isnumeric():
            return int(my_input)
        else:
            return None # Or anything else that is appropriate.
get_int_value(my_dict['str_type']) # returns int 1
get_int_value(my_dict['int_type']) # returns int 1
get_int_value(my_dict['bad_str_type']) # returns None

Using EAFP:

def get_int_value(my_input):
    if isinstance(my_input, int):
        # It is already an integer
        return my_input
    elif isinstance(my_input, str):
        # Needs to be converted
        try:
            return int(my_input) # If it is int like there's no problem
        except ValueError:
            # It wasn't int like
            return None # Or anything else that is appropriate.
get_int_value(my_dict['str_type']) # returns int 1
get_int_value(my_dict['int_type']) # returns int 1
get_int_value(my_dict['bad_str_type']) # returns None
  •  Tags:  
  • Related