0
Why is the output “male” and not “female”?
Hello. The answer is probably very obvious but I don’t get it. Why does it output “Male” here? Isn’t the code supposed to proceed to the next “else”? https://code.sololearn.com/cP13S17hRQ1c/?ref=app
14 ответов
+ 6
Hamsdino
You must explicitly express your comparison to get a a correct boolean result.
You did not compare the "m" against sex, so it elevated as True in your first condition, thus printing Male
sex = "F"
if (sex == "M" or sex =="m"):
print("Male")
else:
print("Female")
+ 7
Rik Wittkopp are you advising to fix the code with: if (sex == ("M" or "m")):?
That would fail. Due to short circuit logic, that reduces to: if (sex == ("M")): and would not work as intended when sex = "m".
Better advice would be:
if sex in ("M", "m"):
+ 5
Hamsdino
You could also use paranthesis to group your conditions together for the single comparison
sex = "F"
if (sex == ("M" or "m")):
print("Male")
else:
print("Female")
+ 5
Python interprets everything except 0 as True.
I think the reason is because it exists
+ 4
@Hamsdino, any non empty string is evaluated to True, only empty string is considered False. See following page for more examples: https://www.freecodecamp.org/news/truthy-and-falsy-values-in-JUMP_LINK__&&__python__&&__JUMP_LINK/
+ 4
=> to get familiar with True, False, as well as with truthy and falsy values or expressions, i recommend to read:
Truthy and Falsy Values in Python: A Detailed Introduction:
https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/
in short: all of them are falsy values:
data structures and types:
empty lists, tuples, dictionaries, sets, strings, bytes, ranges
numbers:
zero of integers, floats, complex
objects
...
+ 3
Rik Wittkopp Thanks that makes sense!
Do you know why a single letter is interpreted as True? Does it get interpreted as
“m” == “m”?
+ 2
Or you can do it like this
https://code.sololearn.com/c99n8R44NLs6/?ref=app
+ 2
+ 1
sex = input()
print("Male") if sex in ("M", "m") else print ("Female")
0
cause coding ain't about genders
0
Brian Thanks for fixing that second option. This one works. So there is no way to use “or” in this case?
0
LIMO lmao it was just a code challenge
0
Uwltoamym Smart advice