You should make the full comparison, it doesn’t work the way you’re imagining it. The or
expects as operating on each side a boolean result. One of the ways to get one is by doing a comparison operation, as you did in the first comparison by testing if the variable is equal to a given text. In the second comparison of or
You’re not testing anything, you’re just putting "f"
, nothing is compared in fact, there is an operation that results in a boolean.
Python is a strong typing language, more or less, there are cases that she screws up there, and this is one of them. Python decided that any value except a few specific ones would be considered true if it expected a boolean value and this is what happens "f"
is considered True
and in a comparison of or
all you have True
on one side is considered True
and so enters the block of if
. Switching to a comparison with the equality operator (==
) it really checks if it is the same and then operates correctly and gives the expected result.
I suggest studying boolean logic and understanding how the tokens of the working languages. There is no magic in the written code, it has well-defined rules of why of each thing, it doesn’t happen by chance because that’s why I always tell people to go deeper than what is seen on the surface, otherwise it will always "program" in trial and error, you’ll be able to make some things work, but you’ll never understand why, you won’t be able to create new things.
letra = input("Qual seu gênero:")
if letra == "F" or letra == "f":
print("Feminino")
elif letra == "M" or letra == "m":
print("Masculino")
else:
("sexo invalido")
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I took advantage and simplified the code.
the correct would be, comparison or comparison
– Elton Nunes
When does
if Letra == "F" or "f":
is the same as doingif (Letra == "F") or true:
and independent of the logical result of the premise(Letra == "F")
anything tested with prepositionor true
will always returntrue
implying that the sentenceLetra == "F" or "f"
always return true and theif
always fall on the first case.– Augusto Vasques