2016-11-20 39 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

'如果(「被砸「)或(」屏幕「)或(」放棄「):」這不是你想要的。如果(「粉碎」)總是評估爲「真」。你想要:「如果」用文字或「屏幕」砸碎了「單詞」或「丟棄」單詞:'(並相應地修復'elif' – UnholySheep

+0

@UnholySheep謝謝! – 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

好有相當多的看到這裏,讓我們去逐一:

  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 
    
相關問題