2016-11-05 57 views
1

我使用的是python 2.7,我对python非常陌生。我想知道为什么我的代码中的行被忽略,尽管我没有看到它们的原因。我的代码中的行被跳过,我不知道为什么

我的代码如下所示:

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 

当我运行的代码,并输入一个动作,是不是在模式的列表,它不会打印出“操作:添加,检查,退出”并且似乎像下面看到的那样跳过。

Input Action: 
k 
Input Action: 

如果我改变代码所看到其下按预期工作:

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 

输出:

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

从我的理解,我认为当一个if语句假,if语句内的代码被跳过,并且后面的代码应该运行,但由于某种原因,这似乎并不是这种情况。是否有这样的理由,或者我对if语句的理解是否有误?

+0

尝试在模式或动作=='退出'的动作 – Copperfield

回答

2

条件action in modes or ['exit']评估为True,不管action的值如何。它看起来像(action in modes) or (['exit'])(所以你应用or运算符操作数action in modes['exit'])。非空列表['exit']在布尔上下文中计算为True,所以or返回True。建议您在这里使用action in modes or action == 'exit'来实现您的目标。

+1

'模式'是一个字典,而不是一个列表 – Copperfield

+0

@Copperfield,谢谢,修正了这一点。 –

相关问题