+ 8
sex="F" if(sex=='M'or'm'): print(female) else: print(male)
anyone explain this code why output get female
14 Respostas
+ 24
Comparison operations (e.g. ==) all have higher precedence than the logical operations "or", "and", "not".
The if condition in your code can be rewritten equivalently with parenthesis as follows.
if (sex == "M") or "m":
Python treats "m" as True.
if (sex == "M") or True:
This "if" condition always evaluates to True.
+ 12
Try this:
sex = "F"
if(sex == "M" or sex == "m"):
print("female")
else:
print("male")
+ 9
MD àŠ°àŠżyad and Mr. Fresher Take a look at all the answers posted by Diego Acero and the answer posted by Jesus David Contreras Avila .
They have both explained that line 2 will always evaluate as true.
It's because python evaluates the "truthiness" of the string 'm' to be true.
As both Diego and Jesus also stated, the fix involves changing line 2 such that 'm' is being compared to the variable as well.
In other words, you cannot combine equality expressions simply by adding an or. Each expression must stand on its own.
For example: This code will always evaluate as true.
age = 1
if(age == 2 or 3)
print("I'm 2 or 3")
However, this will evaluate as false, which is expected:
age = 1
if(age == 2 or age == 3)
print("I'm 2 or 3")
+ 5
#Use sex.upper()
#when sex == "f" or "F", sex.upper() == "F"
#when sex == "m" or "M", sex.upper() == "M"
sex = "F"
if(sex.upper() == "M"):
print("female")
else:
print("male")
+ 3
Mr. Fresher
No matter what the user inputs, your code will always output âmaleâ. Try it out for yourself.
+ 2
line #2: edit
if(sex=='M' or sex=='m'):
line #3 edit and ident tab
print("female")
+ 1
Diego Acero Thank you so much..
+ 1
Youâre welcome. Happy coding!
+ 1
Mr. Fresher
Your code will always output "male".
+ 1
I use this
Sex = "F"
If(Sex == "M") or (Sex == "m"):
Print("female")
Else:
Print("male")
This is going to work..
0
Diego Acero i want the explanation bro..., which exp execute first
0
Try this code bro....
sex="F"
if(sex=='M'or'm'):
print("male")
else:
print("female")
0
Exactly... But if you want input from user, try this code.
sex=input("Enter your sex\n please type only m or f")
if(sex=='M'or'm'):
print("male")
else:
print("female")
- 1
sex="F"
if(sex=='M'or'm'):
print(female)
else:
print(male)
anyone explain this code why output get female