Home > Net >  How does one use parenthesis in if statements with "and" and "or" to separate tw
How does one use parenthesis in if statements with "and" and "or" to separate tw

Time:09-24

Why can you not use the if statements with parenthesis to separate the two or options as shown below? Is there some rule or intricacy of the python program that I am neglecting?

if mass >= 2.6 and (sodium or nitrogen) <= 5:

CodePudding user response:

and and or are operators, just like arithmetic and comparison operators. That means they have one operand on either side and resolve to a single value, which may be an operand for another operator.

Complex, English-like expressions are difficult to implement and can result in strange interactions that are hard for programmers to read, even if they know all the grammar rules. That's why you shouldn't assume that Python expressions work like English, unless you really know what you're doing.

Here is a possibly related question. It deals specifically with logical operators: How to test multiple variables against a single value?

CodePudding user response:

I assume you have three numeric variables: mass, sodium, and nitrogen, and you want to compare them against some border values. Then, your condition should look like "if ((mass >= 2.6) and ((sodium <= 5) or (nitrogen <= 5))):" Actually, I think you can omit everything except the brackets after AND and below colon. However, I personally prefer to leave them explicitly so you have a clear grouping (whuch is probably not recommended by Python guidelines, but works).

If I got it right, your error is that you are trying to use OR between your numeric variables and then compare the result against 5, while you should be comparing each of the variables against 5 and then use OR to process Boolean results you got on step 1.

  • Related