Butterlands
Butterlands

Reputation: 23

unsupported operand type(s) for /: 'instance' and 'int'

Im trying to make a program that finds whether a number is prime or not.

File 2:

class Number():
    def __init__(self, x):
        self.x = float(x)
    def is_prime(x):
        x = x
        Div = 2
        while ((x / 2) > Div):
            if(x == 2):
                return True
            elif(x == 3):
                return True
            else:
                while((x / 2) > Div):
                    if(x%Div == 0):
                        return False
                    elif(Div >= (x / 2)):
                        return True
                    else:
                        Div = Div + 1

File 1:

from File2 import *

N = Number(10)

print N.is_prime()

When I run it I get this:

Traceback (most recent call last):
File "File 1", line 5, in <module>
print N.is_prime()
File "File 2", line 19, in is_prime
while ((x / 2) > Div):
TypeError: unsupported operand type(s) for /: 'instance' and 'int'

Anyone know how to fix this?

Upvotes: 1

Views: 5545

Answers (3)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52163

You are actually trying to do self / 2. Parameter x points to self and since it is the instance of a Number class, you are getting this error.

You need to replace x passed to your method with self.x and change the method's signature to that:

def is_prime(self):
    x = x # remove this
    Div = 2
    while ((self.x / 2) > Div):
        ....

Upvotes: 2

xnx
xnx

Reputation: 25528

@Daniel Roseman has addressed the syntax problems with your class definition. Here's a correction to your chosen algorithm itself, which as it stands returns None (which is what a function returns if it exits without encountering an explicit return statement) if x is prime, and identifies 4 as a prime number. Your nested while loops are not necessary. Try:

class Number():
    def __init__(self, x):
        self.x = float(x)
    def is_prime(self):
        x = self.x
        if(x == 2):
            return True
        elif(x == 3):
            return True
        else:
            Div = 2
            while((x / 2) >= Div):
                if(x%Div == 0):
                    return False
                else:
                    Div = Div + 1
        return True

for i in range(2,36):
    N = Number(i)
    print i, N.is_prime()

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599630

Your syntax is very confused. The first parameter to an instance method in any Python class is always the instance itself, usually called self. Just because you've called the argument x doesn't make it the actual attribute x that you set originally: you would have to refer to x.x. But better to use the standard names, and reference self.x:

def is_prime(self):
    x = self.x

Upvotes: 4

Related Questions