2016-11-17 32 views
0

這是我的代碼,我遇到的問題是它沒有從IF語句排序到ELIF有什麼方法可以解決這個問題嗎?基本上它沒有「或」部分,但它不會在您添加或部分時使用。這與其他問題不同,因爲它使用的是字符串,而另一個問題使用整數。即使不滿意,我的IF也不會移動到ELIF

import time 
print "Welcome to the Troubleshooting Program" 
time.sleep(0.2) 
query=raw_input("What is your query? ") 
querystr=str(query) 
if "screen" or "Screen" in querystr: 
    in_file=open("Screen.txt", "r") 
    screen_answer=in_file.read() 
    print "We have identified the keyword Screen, here are your possible solutions:" 
    time.sleep(0.5) 
    print screen_answer 

elif "wet" or "Wet" or "water" or "Water" in querystr: 
    in_file2=open("Wet.txt", "r") 
    screen_answer=in_file.read() 
    print "We have identified that the device has been in contact with water, here are your possible solutions:" 
    time.sleep(0.5) 
    print screen_answer 

elif "Bath" or "bath" or "sink" or "Sink" or "toilet" or "Toilet" in querystr: 
    in_file3=open("Wet.txt", "r") 
    screen_answer=in_file.read() 
    print "We have identified that the device has been in contact with water, here are your possible solutions:" 
    time.sleep(0.5) 
    print screen_answer 

elif "battery" or "Batttery" or "charge" in querystr: 
    in_file=open("Battery.txt", "r") 
    screen_answer=in_file.read() 
    print "We have identified that there is an issue with the devices battery, here are your possible solutions:" 
    time.sleep(0.5) 
    print screen_answer 

elif "speaker" or "Speaker" or "Sound" or "sound" in querystr: 
    in_file=open("Speaker.txt", "r") 
    screen_answer=in_file.read() 
    print "We have identified that there is an issue with the devices speakers, here are your possible solutions:" 
    time.sleep(0.5) 
    print screen_answer 

elif "port" or "Port" in querystr: 
    in_file=open("Port.txt", "r") 
    screen_answer=in_file.read() 
    print "We have identified that there is an issue with the devices ports, here are your possible solutions:" 
    time.sleep(0.5) 
    print screen_answer 

else: 
    repeat=raw_input("Do you have another query? Y/N") 
    if repeat =="Y" or "y": 
     queryloop() 
    else: 
     print "Thank you!" 

謝謝你的時間。

+2

「屏幕」爲真,那麼第一個條件總是得到滿足。你需要在querystr或querystr中的「Screen」中設置「screen」。或者在querystr.lower()'中輸入「screen」。 –

+1

非常感謝,這已經修復了我的代碼。 –

+0

每個OR之間是一個條件。一個條件必須評估爲真或假,但你擁有的只是一個字符串,它總是會評估爲真,因爲這就是python的工作原理。 貌似你試圖檢查,如果事情是等於在這種情況下,你應該使用 事情的另一件事==「另一回事」 或者你可以只用通過所有的手術室,並使用返回功能一個布爾值。這就是我會做的。該函數可以獲取一個字符串列表並查看它們中的每一個,並檢查它們是否在查詢中 –

回答

0

問題在這裏:

您的條件:

if "screen" or "Screen" in querystr: 

永遠是True因爲:

"screen" or "Screen" in querystr 

總是會返回"screen"和你if會將其視爲True

怎麼辦?

如果你想檢查一些詞是否在querystr或不。你可能不喜歡它:

if any(word in querystr for word in ["screen", "Screen"]) 

在這種特定情況下,由於只是要檢查的條件忽略的情況下,可以寫成:

if "screen" in querystr.lower(): 
相關問題