Check user_input if token is in loop

I am trying to write a function that checks my data to see if I have entered the '?' Character.

This is what I got so far:

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 == '?':


My details: hello? It is supposed to show "Error". But that doesn't show anything. Could you please tell me what is wrong in my code.


source to share

3 answers

I would use an operator in

for this

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


for example

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




The problem is how you split the string user_input




There are no spaces in the example so the condition is not met. If you want, for example, to test a sentence with spaces, you must split it like this: user_input.split(' ')

to split it into spaces.

But for this example, you have two options:

1) You can just iterate over the input itself, because you want to check every char in the string to see if it is ?


That is, change user_input.split():

to just user_input

no separation. This option is good if you ever want to add some kind of action for each char.

2) Very easy to use in

, for example:

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


This is a very simple solution that you can expand and check for other characters in the string as well.



This is because it user_input.split()

separates the space user_input

. Since hello?

it contains no spaces, token

is equal to your input and the loop is executed once.

Instead, it should iterate over user_input

or just check if '?' in user_input




All Articles