2016-11-05 6 views
1

私はpython 2.7を使用しています。私は自分のコード内の行がスキップされている理由を知りたいと思っていましたが、その理由はわかりません。私のコード内の行がスキップされている理由が分かりません

私のコードを以下に見られている:私はコードと入力モードのリストにないアクションを実行すると

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文があるときと思いましたfalseの場合、ifステートメント内のコードはスキップされ、その後のコードは実行される必要がありますが、何らかの理由でここではそうではありません。これには理由があるのですか、またはif文の理解が間違っていますか?

+0

'モードやアクションでのアクション== 'exit'' – Copperfield

答えて

2

条件action in modes or ['exit']は、actionの値にかかわらず、Trueと評価されます。 (action in modes) or (['exit'])のようになります(orオペレータをオペランドaction in modes['exit']に適用します)。空でないリスト['exit']は、ブール値コンテキストでTrueと評価されるため、orTrueを返します。あなたの目標を達成するためにここにaction in modes or action == 'exit'を使用することをお勧めします。

+1

' modes'はリストではなく辞書です – Copperfield

+0

@Copperfield、ありがとう、それを修正しました。 –

関連する問題