2016-11-05 61 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,謝謝,修正了這一點。 –

相關問題