Logic evaluation in an if statement


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/en/courses/python-beginner-en-cxMGf/1/4

<In what way does your code behave incorrectly? Include ALL error messages.>
1
if (char == “A”) or (char ==“a”):
this is true if char is “A” or “a”

2
if char == (“A” or “a”):
This is true only if char is “A”. In the exercise, “X” is substituted when char is “A”, but not “a”

3
if (char == “A” or “a”):
This is always true

<What do you expect to happen instead?>

For 3, the “or” evaluated after the comparison “==” . Correct?

For 2, I don’t see the behavior I expect. What are the rules for order of operations within flow control statements like ‘for’ or ‘if’?

```python

Replace this line with your code.

<do not remove the three backticks above>

#2

Parentheses always go first, so (“A” or “a”) will be evaluated first. This evaluates to "A" given its the first true statement in this comparision. then "A" is compared with char

this breaks down into two comparisons:

char == “A”

and

"a"

which python does first, doesn’t really matter, but i assume left of the or operator. But given strings are considered true if not compared to anything, this condition is always true


#3

Yes, that is in fact what Python does. With an or operation, if the first operand evaluates to True or something equivalent to that, the second operand does not get evaluated at all. In cases where both operands are calls to functions that each have side effects, this short circuiting might matter.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.