Problems with the While repetition structure

1

I'm trying to create a program based on the% rewrite structure, but the loop does not end.

sexo = str(input('Digite seu sexo:'))
if sexo != 'M' or sexo != 'F':
    while sexo != 'M' or sexo != 'F':
        sex = str(input('Digite seu sexo:'))
else:

I also tried to create a def function for while but I could not, if it is possible also use this function in the explanation.

    
asked by anonymous 21.11.2017 / 18:08

1 answer

2

Let's simplify (sorry that Python does not have a do or repeat :

while True:
    sex = input('Digite seu sexo:')
    if sex == 'M' or sex == 'F':
        break

Do you want to continue doing it that way?

sex = input('Digite seu sexo:')
while sex != 'M' and sex != 'F':
    sex = input('Digite seu sexo:')

Did you notice the difference?

It is or that has turned and . When you are going to reverse a condition you have to invert all operators. The opposite of == is != , the opposite of or is and .

Obviously if you want to put if again, you can, as long as the condition is corrected. I found that it has no utility there, but may have another piece of code that may require it, but I would still do otherwise.

The condition you are trying to make is that something comes out of repetition when you type what you want, right? Then it will end the loop when typing M OR F , it's there in if of my first code.

When you want to say a condition that should indicate that the loop should continue repeating, which is the case of while (it continues when it is true), you have to do the inverse of the condition that determines the output. Then you want it to continue whenever you enter something other than M E than F .

If you use an OU there, M is different from F , and you can not have typed both characters at the same time, then the condition would always be true because either the first would be different or the second would be different, it can not be different.

    
21.11.2017 / 18:11