hackerman
hackerman

Reputation: 11

For loop in python is ignoring the if statement

I'm new to python, and I can't see why my for loop is ignoring the if statement and saying every number is a prime number. My code is as such.


def prime_number(number):
    sqrt_prime = math.sqrt(number)
    for x in (2,sqrt_prime-1):
        if isinstance((number/x), int) and x <= sqrt_prime-1:
            con_num = str(number)
            print(con_num,end=' ');print('is not a prime number.')
            break
    else:
        con_num = str(number)
        print(con_num,end=' ');print('is a prime number.')

It could probably be a lot more streamlined, just want to know why it isn't either outputting true for the isinstance or that x is smaller or equal to the sqrt of the number - 1. Thanks in advance.

Upvotes: 1

Views: 85

Answers (2)

Frank
Frank

Reputation: 1249

The problem is isinstance((number/x), int).

The type is always float if you check them by

print(type(number/x))

Correction: Change it from

        if isinstance((number/x), int) and x <= sqrt_prime-1:

to

        if number % x == 0 and x <= sqrt_prime-1:

Another problem is the coding:

def prime_number(number):
    sqrt_prime = math.sqrt(number)
    flg = 0
    for x in (2,sqrt_prime-1):
        if number % x == 0 and x <= sqrt_prime-1:
            con_num = str(number)
            print(con_num,end=' ');print('is not a prime number.')
            flg = 1
            break
    if flg==0:
            con_num = str(number)
            print(con_num,end=' ');print('is a prime number.')

I am not sure if you have finished the code, seems like this is algorithm is not running rightly.

Upvotes: 0

astrochun
astrochun

Reputation: 1796

If this is python 3.x then it makes sense why it ignores it.

number/x will always return a float and not an integer. Thus, isinstance((number/x), int) is always False.

Upvotes: 1

Related Questions