Reputation: 13
From the question I’m about to ask you will realize that I’m just a beginner. Anyways, so I’m assigning a input function to a variable word
. I then def a function and in that function I say:
if ' ' or '-' in word:
print('Error cannot...')
My issue here is whenever I run this and enter a word for my input it always prints Error cannot...
even when I don’t have spaces or '-'
in my word. That’s all thanks if you decide to help me out.
Upvotes: 1
Views: 96
Reputation: 1
you have wrong logic or
return True if one or more statements are True.
In you case you can solve it in different ways.
if " " in word or '-' in word:
print('Error cannot.....')
Either you can have a list of characters which can iterate through the word to check whether a word contains any of those characters. For example
l = ['-',' ']
for c in l :
if c in word:
print('Error....')
break
Upvotes: 0
Reputation: 8747
The or
operator must compare two boolean values. So when you do
if ' ' or '-' in word:
Python will convert both sides of the or
into boolean values (True
or False
).
The problem here is that the left side of the or
is just ' '
, which in Python is considered 'truthy' (in an if statement it will evaluate to True
). So what you're really doing here is
if True or '-' in word:
which will always be True
. (True or anything
is always True
no matter what anything
is).
What you most likely intended was
if ' ' in word or '-' in word:
Upvotes: 1
Reputation: 2370
Try using this: if " " in word or "-" in word:
. The reason you got the outcome you did is because a non-empty string is "truthy," in other words, it is considered true. If you have true on one side of an or and false on the other, the or will still output true.
Upvotes: 3