+ 1
Can someone explain me that why the answer is Male
sex="F" if (sex=="M" or"m"): print("Male") else: print("Female")
6 ответов
+ 9
Your if condition is a logical expression.
Left side of "or": sex == "M"
Right side of "or": "m"
The right side is a nonempty string which is always evaluated to True. So your condition always ends up True, regardless of the variable.
Possible fixes:
if sex == "M" or sex == "m":
if sex in ("M", "m"):
if sex in 'Mm':
If this is Python, then you don't have to put parentheses around the expression. The in operator allows you to check for multiple values at the same time, and checking a letter works with a list or tuple of characters as well as a string (of characters).
+ 3
In Python, "var==smth or smth2" returns true, no matter the variable "var" is equal to smth or smth2 OR NOT. This is because the 2nd condition is empty(Not including the smth2), so it is evaluated to True, the "or" operator will return true if either one of the condition is True. You have to write a little further so that the code know what you're doing. And in Python, you don't have to write the condition in parentheses "()"! These are only for other languages like Java or C++,etc..
To execute the else statement if the condition is False, you have to write it like:
```
if sex == "M" or sex == "m":
```
(This if condition would be false if the variable "sex" is not equal to "M" or (the variable "sex" is not equal to) "m".)
In the example above, it has 2 condition, and you have to write each condition carefully. Attempting to pass a value(except bool value) in an if condition, without writing other things in it (e.g: "if 6 or 5:", "if 9:"), the if condition will be executed(May not true for "and" operator).
+ 2
Tibor Santa thank you ☺️
+ 1
Dragon RB thank you so much sir.
+ 1
Piyush Prajapat No problem.
Anyways, next time when sending your code to offer for help in the Q&A Discussions, PLEASE link us to your code so we can see the output directly, instead of pasting it in the description of your question! And make good use of tags(Use a few words to describe the question in the tags)!!
Use search engine to search your question, if it is asked and answered before. If it is not, please post it here.
+ 1
Ohk btw I am new here and I used search engine, but I didn't understand there. That's why I thought to post it here.