Tofuistofu
Tofuistofu

Reputation: 21

Lines in my code being skipped and I am not sure why

I am using python 2.7 and I am pretty new to python. I was wanted to ask why lines in my code are being skipped although I don't see a reason for them to be.

My code is seen below:

def add_client:
    code for adding client

def check_clients:
    code for listing out client info

modes = {'add': add_client, 'check': check_clients}        
while True:
    while True:
        action = raw_input('Input Action: \n').lower()
        if action in modes or ['exit']:
            break
        print 'Actions available:',
        for i in modes:
            print i.title() + ',',
        print 'Exit' 

    if action in modes:
        modes[mode](wb)

    if action == 'exit':
        break

When I run the code and input an action that is not in the list of modes, it does not print out 'Actions available: add, check, exit' and just seems to skip like seen below.

Input Action:
k
Input Action:

If I change the code to what is seen below it works as intended:

modes = {'add': add_entries, 'check': check_stats}        
while True:
    while True:
        mode = raw_input('Input Action: \n').lower()
        if mode not in modes:
            print 'Actions available:',
            for i in modes:
                print i.title() + ',',
            print 'End/Exit' 
        if mode in modes or ['end', 'exit']:
            break

    if mode in modes:
        modes[mode](wb)

    if mode in ['end', 'exit']:
        break

Output:

Input Action:
k
Actions available: Add, Check, End/Exit

From my understanding, I thought that when an if statement is false, the code within the if statement is skipped and the code following should be ran, but for some reason, this doesn't seem to be the case here. Is there a reason for this or is my understanding of the if statement incorrect?

Upvotes: 1

Views: 57

Answers (1)

Ilya V. Schurov
Ilya V. Schurov

Reputation: 8077

The condition action in modes or ['exit'] evaluates to True regardless of the value of action. It read like (action in modes) or (['exit']) (so you apply or operator to operands action in modes and ['exit']). Non-empty list ['exit'] evaluates to True in boolean context, so or returns True. You are suggested to use action in modes or action == 'exit' here to achieve your goal.

Upvotes: 2

Related Questions