Why does not my while work?

1

I'm studying repetition structure and in one of the exercises I had to check the sex typed, so I made the following code:

sexo = input("digite m ou f: ")
while sexo != 'f' or sexo != 'm':
   sexo = input("digite m ou f: ")

However, it does not work.

What am I doing wrong?

    
asked by anonymous 22.08.2017 / 14:15

2 answers

11

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.

    
22.08.2017 / 14:20
1

Your stop condition is as follows: while sexo != 'f' or sexo != 'm': , that is, when the user types something other than 'f' or 'm', it remains in the loop, and he will never type a letter equal to both. p>

In order for him to exit with one of the accepted options, his condition must be to continue while he does not type one or the other:

sexo = input("digite m ou f: ")
while sexo != 'f' and sexo != 'm':
     sexo = input("digite m ou f: ")
print(sexo)
    
22.08.2017 / 14:21