pythoncontrol-flownested-iflogic-error

how to avoid logic errors in python using the control flow and nested if statements?


I'trying to write code that helps you decide whether you should or shouldn't eat food if you have droppped it. But it doesn't print the decision if too many conditions are met e.g if someone who is a boss/lover/parents has seen me droping the food and if the food isn't expensive and it's chocolate. What is wrong with my code ?? / / See code below / /

decision = ''
condition1 = ''
condition2 = ''
condition3 = ''
condition4 = ''
condition5 = ''
condition6 = ''
condition7 = ''

condition1 = input('Did anyone see you? (yes/no)' + '\n')
if condition1 == 'yes':
    condition2 = input('Was it a boss/lover/parent? (yes/no)' + '\n')

    if condition2  == 'no':
        decision = 'Decision: Eat it'   
    elif condition2 == 'yes':
        condition3 = input('Was it expensinve? (yes/no)' + '\n')
    
    if condition3 == 'yes':
        condition4 == input('can you cut the part that touched the floor? (yes/no)' + '\n')
    if condition4 == 'yes':
        decision = 'Decision: Eat it.'
    elif condition4 == 'no':
        decision = 'Decision: Your call'
    elif condition3 == 'no':
        condition5 == input('Is it chocolate? (yes/no)' + '\n')
    if condition5 == 'no':
        decision = "decision: Don't eat it"
    elif condition5 == "yes":
        decision = 'Decision: Eat it'
    
elif condition1 == 'no':
    decision = 'Decision: Eat it'
print(decision)

I tried nesting my if statements so that python can make a decision based on the conditions that are met or when they are't met. And at the end print the decision. i was expecting python to decide for me whether i should or shouldn't eat the food that I dropped.


Solution

  • You might want to look at getting rid of the arrow pattern in your code by looking for more opportunities to cleanly come to a decision. I like to use guards to aid this. I think this does the same thing as your code but it is easier (for me) to follow and I find it easier to see where there might be logic holes.

    def should_i_eat_it():
        if "no" == input("Did anyone see you? (yes/no) "):
            return "Eat it"
    
        if "no" == input("Was it a boss/lover/parent? (yes/no) "):
            return "Eat it"
    
        if "yes" == input("Was it expensinve? (yes/no) "):
            if "yes" == input("can you cut the part that touched the floor? (yes/no) "):
                return "Eat it"
            return "Your call"
    
        if "yes" == input("Is it chocolate? (yes/no) "):
            return "Eat it"
        return "Don't eat it"
    
    print(should_i_eat_it())