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
>>>
正如您所看到的,无论用户输入什么,它都只显示代码的顶行。
答案 0 :(得分:1)
您的第一个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])
条件存在问题。
请尝试以下方法:
String strRx = "";
int c = 0;
int k = 0;
//BLuetoothi pakettide vastuvõtmine ja ekraanile panek
while (true) {
try {
//Mingi data tuleb, seega ekraanile
if (connectedInputStream.available() > 0) {
bytes = connectedInputStream.read(buffer);
final String strReceived = new String(buffer);
runOnUiThread(new Runnable() {
@Override
public void run() {
// textStatus.append(strReceived);
textStatus.setText(strReceived);
String strReceivedCut=strReceived.substring(0,8); //Lõikab stringist esimese osa välja
boolean resultOfComparison=new String("EMPTYING").equals(strReceivedCut);
if(resultOfComparison==true) {
testkast.setText("It Happened");
//long timeNow= System.currentTimeMillis(); //Praegune hetk
//long startTime = System.currentTimeMillis();
//if(timeNow-startTime>1000*60*10) { //Should be 10 minutes
new UploadBySSH().execute(strReceived); //Saadame algse stringi SSH-ga servusse
//}
}
}
});
//Mingit datat ei tule, seega ootame Sleep
} else SystemClock.sleep(100);
//Keepalive osa, mis saadab ? mingi aja tagant
//hetkel on ajaks 10*100=1000 millisekundit
//Originaal programmi keepalive:
//;E??????????;E??????????;E??????????;E??????????;E??????????;E??????????
c++;
if (c > 10) {
String kl = "?";
byte[] bytesToSend = kl.getBytes();
connectedOutputStream.write(bytesToSend);
c = 0;
k++;
}
} catch (IOException e) {
e.printStackTrace();
final String msgConnectionLost = "Ühendus nurjus: PANE PROGRAMM KINNI\n"
+ e.getMessage();
runOnUiThread(new Runnable() {
@Override
public void run() {
textStatus.setText(msgConnectionLost);
}
});
}
}
}`
答案 1 :(得分:-1)
好的,有很多可以看到这里,让我们一一去:
if
语句采用可简化为布尔值的表达式(True / False)。通过或/分隔不同的语句以实现更严格的逻辑
如果我想查看列表中是否有以下任何单词,例如:
# ( ) ( ) ( )
if 'wet' in words or 'smashed' in words or 'dropped' in words:
...
由于这是多余的,我们可以尝试使其更灵活(和可扩展)。
words = ['wet', 'smashed', 'dropped']
if any(word in words for word in cur_line):
...
然后我们需要确保每一行都发生这种情况,因此我们应该遍历每一行并应用相同的逻辑......
words = ['wet', 'smashed', 'dropped']
for cur_line in line:
if any(word in words for word in cur_line):
print cur_line