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 == '?':
print('Error')
check_word()
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
The problem is how you split the string user_input
.
user_input.split():
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.
source to share