Home > other >  Python If Statement missing the else clause?
Python If Statement missing the else clause?

Time:07-16

Super newbie question: why does option 1 and 2 come up with different values? The only difference is there is an else before output[item] = output[item] 1 in the second option. I'm not clear about what option 1 is doing.

Option 1:

def item_count(input):
    output = {}
    
    for item in input:    
        if item not in output: 
            output[item] = 0
        
        output[item] = output[item]   1
        
    return output

Option 2

def item_count(input):
    output = {}
    
    for item in input:    
        if item not in output: 
            output[item] = 0
        
        else:
            output[item] = output[item]   1
        
    return output

CodePudding user response:

This is because in your first code snippet there is an if statement followed by output[item] = 0, since this second bit of code is not wrapped in an else block it will always be executed after the initial if block no matter what.

However, in your second code block, the output[item] = 0 is wrapped in an else block. This means, that the line will only be executed if the if block does not run. Simply, in the second code block, the if and else are mutually exclusive. Both can’t be executed.

CodePudding user response:

In your option 2, the if and else serve as "either or", which means the code will only execute one of them: execute the if clause if item not in output or the else clause if the item is in the output.

However, in your option 1, the output[item] = output[item] 1 will always get executed no matter what happened in the if clause.

  • Related