+ 2

Please can someone explain the meaning of this code to me. I found it as a question in one of the python challenges.

x="F" if x=="M" or "m": print ("Male") else: print ("Female") #output :Male

4th Mar 2018, 2:31 PM
philip appiah
philip appiah - avatar
5 odpowiedzi
+ 3
Solve 1 expression at one time. 1st: x == "M" leads to False, which you may already know it. 2nd: "m" leads to something present. When you use value alone in 'if' statement, 'if' statement check whether something is present or not. In this case it is "m" present. So 2nd expression lead to True. If the value is something like " "(or)"[]" which is empty value, then expression will lead to False. Then above if statement would be: if False or True , which lead to True finally. So output become 'Male'.
4th Mar 2018, 2:43 PM
Sylar
+ 2
because of the "or "m"" because it will only return True you can test this by just if "abc": print("True") correct statement would be if x == "m" or x == "M":
4th Mar 2018, 2:44 PM
Markus Kaleton
Markus Kaleton - avatar
+ 1
Thank you very much Sylar. I now get the concept.
4th Mar 2018, 2:46 PM
philip appiah
philip appiah - avatar
+ 1
You're welcome :) Happy coding philip!!
4th Mar 2018, 2:48 PM
Sylar
+ 1
tnx Markus Kaleton
4th Mar 2018, 2:51 PM
philip appiah
philip appiah - avatar