If statements and while loops

Hey everyone, I’ve been working on this program for a class assignment and I can’t seem to figure out this problem with my if statements and while loops. For some reason this code will only calculate for the first variable, or the “men” if statement. Attached are the two different ways I’ve tried to implement this and it still only calculates depending on which if statement I wrote first.

Welcome!

Please post code as text not pictures. Its very hard to read the images.
See About the Python Help category for how to do this.

if sex == 'men' or 'Men':

Is executed as this; the or 'Men' part is always True.

if (sex == 'men') or 'Men':
# becomes
if (sex == 'men') or True:
# becomes
if True:

You can write that a number of ways depening on you needs:

if sex == 'men' or sex == 'Men':
if sex in ('men', 'Men'):
if sex.lower() == 'men':
1 Like

Not really, and think it’s harmful to explain it that way.

What is harmful about this way of doing it?

This worked, thank you so much. I thought it was something much more complicated than that.

@pochmann Can you elaborate? Why do you think this is harmful? What would be a better way to explain this?

The Python parser does parse this as equivalent to

if  ((sex == 'men') or 'Men'): ...

and the ‘Men’ string inside the boolean or will always evaluate to True, so the whole test condition always evaluates to True.

What I meant is that that makes it look like the right operand of or is evaluated first, or maybe the “simpler” operand. And that the left operand isn’t even evaluated there. Which is not the case, and they’d better not learn that (If they do, that would be the harm). The left operand is evaluated first, and the right operand might not even get evaluated at all. The end result is the same here, the if condition is true and evaluating it has no side effect (other than spending time) and the if suite is executed, but that’s not true in general.

(Btw it seems CPython optimizes the right side away during compilation, but that’s an implementation detail, and the left side still does get evaluated when the code runs.)

1 Like

Please see: