Replace the final condition by (p^q-q^p) % 2 == 0 and ((p^q-q^p)//2).is_prime(), so that integer division is used and hence the is_prime method of an integer is called, rather than the is_prime method of a rational number.