In this case you should use and
and not or
. In the current form the condition will always be true because at least one of the two subexpressions will be true, something is impossible to be equal to two different things, one will always be different. If the letter is f
it will be different from m
and if it is m
, it will be different from f
if it is something else, both will be true, but it does not matter, just a being that everything is true. p>
You want to be different from both at the same time, this is with and
, so both must be true to continue in the loop, and it is impossible both to be true if you type either f
or m
sexo = input("digite m ou f: ")
while sexo != 'f' and sexo != 'm':
sexo = input("digite m ou f: ")
print(sexo)
See the truth table to understand the difference between operators. And logical operators in action.
See running on ideone . And no Coding Ground . Also put GitHub for future reference .
I understand the confusion because you want to accept that a or other letter is acceptable. What confuses it is that the loop is asking for the inverse, it is not testing if it accepts one or the other, it is testing if not is one or the other, there you have to invert the operator. If you feel more comfortable you can write in a way that uses or
, many will find that it 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 it does not stay anymore and the result is the same.