Search code examples
pythonstringfunctionif-statementexception

Scripting if-else nesting to select a string type from a list, as python function argument


I have a python function defined as such:

def fun(name=None):
    data = [['tom'], ['nick'], ['juli']]
    
    name0 = data[0]  # tom
    name1 = data[1]  # nick
    name2 = data[2]  # juli
    if name is not None:
        if name=='tom':
            Name=name0
        if name=='nick':
            Name=name1
        if name=='juli':
            Name=name2

    if name is None:
        print('Reading all the names')
        Name=data
    else:
        raise Exception('arguments cannot be empty. Either pass one single name or None')
    return Name

This is a simplified represenation of my actual script. For my workflow I need to call such a function for a specific string type argument Name that is being stored as a list data. Now when I call this function for tom:

fun('tom')

I get the following error:

---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
Cell In[28], line 26
     23         raise Exception('arguments cannot be empty. Either pass one single name or None')
     24     return Name
---> 26 fun('tom')

Cell In[28], line 23, in fun(name)
     21     Name=data
     22 else:
---> 23     raise Exception('arguments cannot be empty. Either pass one single name or None')
     24 return Name

Exception: arguments cannot be empty. Either pass one single name or None 

As you can see the if tree is being skipped and either working with None or the else part is being executed. Why this function is skipping the if tree. Because in one of my earlier script such a logic worked. What am I doing wrong? Thanks in advance.


Solution

  • It looks like there's an issue with your code. The raise Exception block is being triggered even when name is provided. This might be due to the indentation of the block. Try adjusting the indentation like this:

    def fun(name=None):
        data = [['tom'], ['nick'], ['juli']]
        
        name0 = data[0]  # tom
        name1 = data[1]  # nick
        name2 = data[2]  # juli
        if name is not None:
            if name == 'tom':
                Name = name0
            elif name == 'nick':
                Name = name1
            elif name == 'juli':
                Name = name2
        else:
            print('Reading all the names')
            Name = data
    
        return Name
    

    This should resolve the error. Additionally, I replaced the separate if statements for each name with elif to make the code more concise.