Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using IFF in python

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?

like image 709
sid597 Avatar asked Dec 08 '15 14:12

sid597


3 Answers

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):
like image 189
Bill the Lizard Avatar answered Nov 15 '22 13:11

Bill the Lizard


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.

like image 29
Rick supports Monica Avatar answered Nov 15 '22 13:11

Rick supports Monica


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):
like image 32
Wayne Werner Avatar answered Nov 15 '22 14:11

Wayne Werner