2

I'm having some trouble with AND and OR within if else statements. This is my code:

if subject == 'history' or subject == 'History' and unit == 'WWII' or unit == 'ww2':

Any ideas how to fix this?

5
  • 1
    coding hint: userName, subject, unit, score, grade = hisWw2[:5] Commented Dec 31, 2017 at 15:40
  • 3
    At first you should use parentheses to group the logical operators (and, or). The may not always be necessary but in complex expressions they are helpful to understand the expression Commented Dec 31, 2017 at 15:40
  • 1
    also, consider elif Commented Dec 31, 2017 at 15:41
  • 1
    all operators have a "weight" and "assosiativity" - they bind differently strong. Use ( ) to reformulate your logical assumptions so they bind in a way that fits. FALSE and TRUE or FALSE is always FALSE bexause and binds stronger then or does .... use () -- weight is the wrong word - brb - see answer for doku on pythons operators. Commented Dec 31, 2017 at 15:42
  • Yep the brackets are working thanks! I never knew you could put brackets around logic operators. Commented Dec 31, 2017 at 15:48

1 Answer 1

2

Read up on operator-precedence - some operators bind stronnger then others - to get your desired logical output you should use ( ) to structure your logical conditions.

Summarization:

Operator                              Description
lambda                                Lambda expression
if – else                             Conditional expression
or                                    Boolean OR
and                                   Boolean AND
not x                                 Boolean NOT
in, not in, is, is not, <, <=, >, >=, !=, ==  Comparisons, including membership tests and identity tests
|                                     Bitwise OR
^                                     Bitwise XOR
&                                     Bitwise AND
<<, >>                                Shifts
+, -                                  Addition and subtraction
*, @, /, //, %                        Multiplication, matrix multiplication, division, floor division, remainder [5]
+x, -x, ~x                            Positive, negative, bitwise NOT
**                                    Exponentiation [6]
await x                               Await expression
x[index], x[index:index], x(arguments...), x.attribute       Subscription, slicing, call, attribute reference
(expressions...), [expressions...], {key: value...}, {expressions...}     Binding or tuple display, list display, dictionary display, set display

The ealier the operator the higher it binds. Please see the linked doku for subscription context

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.