17

Is there a way to write an iff statement (i.e., if and only if) in Python?

I want to use it like in

for i in range(x)
    iff x%2==0 and x%i==0:

However, there isn't any iff statement in Python. Wikipedia defines the truth table for iff as this:

a |  b  |  iff a and b
-----------------------
T |  T  |      T
T |  F  |      F
F |  T  |      F
F |  F  |      T

How do I accomplish this in Python?

1
  • TIL the technical definition of IFF is the same as XNOR Commented Apr 7, 2022 at 16:55

5 Answers 5

39

If you look at the truth table for IFF, you can see that (p iff q) is true when both p and q are true or both are false. That's just the same as checking for equality, so in Python code you'd say:

if (x%2==0) == (x%i==0):
Sign up to request clarification or add additional context in comments.

Comments

13

According to Wikipedia:

Note that it is equivalent to that produced by the XNOR gate, and opposite to that produced by the XOR gate.

If that's what you're looking for you simply want this:

if not(x%2 == 0 ^ x%i == 0):

Comments

4

The previous answers solve the problem.

As a note of clarification on this: the if statement is only accepting one input, not multiple. So when you do if blah and bleh:, it is equivalent to if (blah and bleh):. The expression blah and bleh is evaluated for truth value first, and that result is then fed to the if statement.

A truth table type of logic evaluation would require multiple inputs (a and b) instead of just one, but if doesn't work that way.

Comments

0

Use the biconditional statement equivalence:

Enter image description here

Comments

-3

I was just wondering the same. Here's a quick fix which worked:

def iff(a, b, c):
    if a:
        return b
    else:
        return c

1 Comment

That's iif not iff

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.