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?
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):
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.
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):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With