2016-11-20 6 views
1
prob = input("Please enter your problem?") 
words = set(prob.split()) 

file=open('solutions.txt') 
line=file.readlines() 
if ("smashed") or ("screen") or ("dropped") in words: 
    print (line[0]) 
elif ("wet") or ("water") in words: 
    print (line[6]) 
else: 
    print("sorry") 

このコードの問題はそれだけでユーザーが入力した単語を含む行をどのように印刷しますか?

ここ

ある結果テキストファイルの先頭行を印刷していることである:

>>> 
============== RESTART: C:\Users\bb\Desktop\completed - Copy.py ============== 
Please enter your problem?smashed 
your screen is smashed 

>>> 
============== RESTART: C:\Users\bb\Desktop\completed - Copy.py ============== 
Please enter your problem?wet 
your screen is smashed 

>>> 
============== RESTART: C:\Users\bb\Desktop\completed - Copy.py ============== 
Please enter your problem?bntuib 
your screen is smashed 

>>> 

あなたはそれが唯一のコードの先頭行が表示され見ることができるようにユーザーが何を入力しても問題ありません。

+2

' ")または("スクリーン ")または("ドロップ ")の単語:'あなたがここで欲しいものではありません。 'if(" smashed ")'は常に 'True'と評価されます。あなたがしたい: '単語を"壊した場合 "または単語を"画面 "または単語を"落とした場合: '(そして、それに応じて' elif'を修正する。 – UnholySheep

+0

@UnholySheep THANKS! – error404

答えて

1

最初のifに問題があります。

代わりに以下のことを試してみてください。

check_list = ["smashed", "screen", "dropped"] # Words to check 

if any(w_ in words for w_ in check_list): # Checks that at least one conditions returns True 
    print (line[0]) 
-1

こちらを見てかなりの数があります[OK]を、のは、一つ一つを手放す:

  1. if文は、ブール値に簡素化することができる表現を取ります(正誤)。より厳密なロジックを実現するには、別のステートメントを/または/で区切ります。
    私は、次のいずれかの単語がリスト内にあるかどうか、たとえば、参照したい場合:

    # (   ) (    ) (    ) 
    if 'wet' in words or 'smashed' in words or 'dropped' in words: 
        ... 
    
  2. これが冗長になっているので、我々はそれがもう少し柔軟(およびスケーラブルな)を作ってみることができます。

    words = ['wet', 'smashed', 'dropped'] 
    if any(word in words for word in cur_line): 
        ... 
    
  3. そして、我々は、これはすべての行のために起こることを確認する必要があり、私たちはそれぞれのラインを介して実行と同じロジックを適用する必要があります...

    「こわれ(場合
    words = ['wet', 'smashed', 'dropped'] 
    for cur_line in line: 
        if any(word in words for word in cur_line): 
         print cur_line 
    
関連する問題