即使不满意,我的IF也没有转向ELIF

时间:2016-11-17 12:11:29

标签: python python-2.7

这是我的代码,我遇到的问题是它没有从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!"

感谢您的时间。

1 个答案:

答案 0 :(得分: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():