In this case you should use a and
and not a or
. In the present form the condition will always be true because at least one of the two sub-expressions will be true, it is impossible for something to be equal to two different things, always one will be different. If the letter is f
she will be different from m
and if it is m
, will be different from f
if it’s something else, both will be true, but it doesn’t even matter, just one being that everything stays true.
The desire is to be different from both at the same time, this is with the and
, so both need to be true to continue in the loop and it is impossible for both to be true if typing or f
or m
.
sexo = input("digite m ou f: ")
while sexo != 'f' and sexo != 'm':
sexo = input("digite m ou f: ")
print(sexo)
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
See the truth table to understand the difference between operators. And logical operators in action.
I understand the confusion because you want to accept that a or another letter is acceptable. What confuses is that the loop is asking the reverse, it is not testing whether to accept one or the other, it is testing whether to nay is one or the other, then you have to reverse the operator. If you feel more comfortable you can write in another way using the or
, many will consider that better expresses the intention:
sexo = ''
while not (sexo == 'f' or sexo == 'm'):
sexo = input("digite m ou f: ")
print(sexo)
Note that I made another improvement. The input
was repeated, so does not stay more and the result is the same.
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.
– Maniero