You cannot use the equality comparator (==
) to check if a list contains a certain element. In this case, you are comparing the list with a value that is not even of the list type. This will always be false unless you compare two equal lists. Further reading.
The error of your code is here:
if maria == ['bom dia', 'BOM DIA', 'Bom dia', 'bom Dia']:
For this you can use the operator in
, thus:
if maria in ['bom dia', 'BOM DIA', 'Bom dia', 'bom Dia']:
But note that your list of expected answers has the same answer. The difference is found only in the box of each letter. In that sense, a better alternative is to convert everything to low box and make only a comparison. So:
if maria.lower() == 'bom dia':
However, if there are answers that vary not only in relation to the box, it will be necessary to compare the response to a number of predefined values.
However, using a list may not always be a good idea for such things, since the method in
makes linear searches. A better alternative is to use a set, that searches on average in constant time. The operator in
is also used. The difference is not by the operator, but by the data structure used.
In the end, you’d have something like this:
print('Olá! Sou Maria, fale comigo!')
resp = input().lower()
# note o erro de digitação no segundo elemento, que também é visto como válido
if resp in {'bom dia', 'bon dia'}:
print('Bom dia! Como você está?')
Note that, unlike lists, which are denoted by square brackets, sets are denoted by keys.
Of course, for a small set of responses, the difference in efficiency is derisory, but as the amount of elements to be compared increases, the difference can be great.
Do
if maria in [...]
– Woss
But it could do
if maria.lower() == 'bom dia'
and so consider any variation of upper and lower case letters of the without example, up to, for example,BOM dia
, that does not exist on the list.– Woss
Hmmm beauty, but in another case q I want to put other possibilities of answer, for example: Maria -> How are you? You -> I’m fine or Fine or To good ?
– orbitB374
You can make a combination of the two...
– Woss
Who is negative does not think it is good to comment on the motivation of -1? What is the problem with the question? It’s really reasonable to expect any new person on the schedule to know thresh a "wrong" behavior that silently fails?
– Luiz Felipe
This answers your question? Python: How to check for an element in a list
– Rafael Tavares