2015-11-20 79 views
1

所以,基本上,这是我的代码:Python的检查用户输入

import random 
import os 

answer = input('What is the problem with your mobile phone? Please do not enter more than one sentence.') 
print('The program has detected that you have entered a query regarding: ' 
if 'wet' or 'water' or 'liquid' or 'mobile' in answer: 
    print('Put your mobile phone inside of a fridge, it sounds stupid but it should work!') 

我想知道的是,比方说,如果用户输入关键字“湿”和“移动”作为其输入,我怎么反馈给他们知道我的程序已经识别出他们的查询。

因此,通过说'如果程序检测到您输入了一个关于以下内容的查询:'我如何将它们的关键字过滤到这句话中,比如说,如果他们输入'我的手机最近变湿了',我想要不用说:

print('The program has detected that you have entered wet') 

因为这听起来很蠢的IMO。

谢谢

+0

把打印语句你'if'测试里面。实际上,你的整个if语句是无效的,需要重新编码。 – user590028

+0

是的,我知道它应该是一个如果不是一个ELIF,我需要删除进口操作系统,我只是想尝试之前为什么有不需要的代码位 – Thom9son

+0

但我想要一种方式来拉特定例如,如果有“有效输入”列表,并且来自用户输入的字符串中的一些字符串与列表匹配,那么它将打印所述字符串。 – Thom9son

回答

1

你可以做到这一点与一个元组,列表和any功能:

SEND_REPORT_TUPLE = ('wet', 'water', 'liquid', 'mobile') 
#make a list from the input 
input_list = answer.split(" ") 
#And then the use any function with comprehension list 
if any(e in SEND_REPORT_TUPLE for e in input_list): 
    print("The program has detected a query...") 
+0

@parthgudhka我认为这是最pythonic的方式,不需要做嵌套循环... –

+0

一个问题,什么是元组? – Thom9son

+0

@ Thom9son *元组是一系列不可变的Python对象。元组是序列,就像列表一样。元组和列表之间的区别在于,不同于列表和元组使用圆括号,元组不能更改,而列表使用方括号。* >>在该示例中,您可以使用元组或列表。 –

2

如果我正确理解你的问题,这应该可以解决你的问题。只需将打印语句放在if条件内!很简单,我想:)

import random 
import os 

answer = input('What is the problem with your mobile phone? Please do not enter more than one sentence.') 
if 'wet' or 'water' or 'liquid' or 'mobile' in answer: 
    print('The program has detected that you have entered a query regarding: water') # or anything else wet or whatever 
    print('Put your mobile phone inside of a fridge, it sounds stupid but it should work!') 
+0

这个工作适合你吗? – Parth

+0

多数民众赞成但事情,我知道该怎么做,这很容易,但不是说有关'水'的查询,我想知道是否有任何方式使用列表或东西从用户句子中挑出字符串和交叉引用它们,如果有任何匹配,它使用它们从列表中打印出来。但是,如果没有匹配,我将要这样做,以便他们可以选择是否向报告编号等技术人员写报告,这只会将一些信息写入文件 – Thom9son

+0

是的,那很好工作,我知道只是看着它,因为我认为只是这样做,但在我看来这似乎很基本 – Thom9son