在循环中使用if标记检查user_input

时间:2015-05-08 11:18:59

标签: python

我正在尝试编写一个检查输入的函数,看看我是否输入了字符'?'。

这是我到目前为止所得到的:

def check_word():
   word = []
   check = 0
   user_input = input('Please enter a word that does not contain ?: ')

   for token in user_input.split():
      if token == '?':
        print('Error')
check_word()

我的意见:你好? 它应该显示'错误'。但它没有显示任何东西。你能否告诉我我的代码中有什么错误。

3 个答案:

答案 0 :(得分:3)

我会使用in运算符来执行此操作

def check_word(s):
    if '?' in s:
        print('Error')

例如

>>> check_word('foobar')
>>> check_word('foo?')
Error

答案 1 :(得分:1)

问题在于如何拆分user_input的字符串。

user_input.split():

该示例不包含空格,因此不满足条件。例如,如果要检查带空格的句子,则应将其拆分为:user_input.split(' ')将其拆分为空格。

但是对于这个例子,你有两个选择:

1)您可以迭代输入本身,因为您要检查字符串中的每个字符是否为?

也就是说,将user_input.split():更改为user_input而不进行拆分。如果您可能希望为每个字符添加某种操作,则此选项很好。

2)使用in非常简单,就像这样:

if '?' in s:
    print('There is a question mark in the string')

这是一个非常简单的解决方案,您可以扩展并检查字符串中的其他字符。

答案 2 :(得分:0)

这是因为user_input.split()按空格分割user_input。由于hello?不包含任何空格,token等于您的输入,循环执行一次。

您应该迭代user_input,或者只需检查if '?' in user_input