0

I am trying to teach myself python by writing a simple program to test if a number is prime or not. It seems to me like the code should work but when I run it I am not getting asked to input a number even though I am using raw_input() like it says to do here, Python: user input and commandline arguments. What should I do to fix this?

class PrimeTester:

    def primeTest(number):
        if number == 2:
            print("prime")

        if number % 2 == 0:
            print("not prime")

        highesttestnum = number ** 0.5 + 1
        count = 3
        while count <= highesttestnum:
            if number % count == 0:
                print("not prime")
            count += 2

        print("prime")

    def __init__(self):
        x = int(raw_input('Input a number to test if prime:'))
        print("The number " + x + " " + primeTest(x))
Community
  • 1
  • 1
user3282276
  • 3,674
  • 8
  • 32
  • 48

2 Answers2

1

You need to create an object of this class after your code.

 x = PrimeTester()

You can also create the object in function and then call this function.

doptimusprime
  • 9,115
  • 6
  • 52
  • 90
1
class PrimeTester:
    def __init__(self):
        x = int(raw_input('Input a number to test if prime:'))
        result = self.primeTest(x)
        print("The number " + str(x) + " is " + result)


    def primeTest(self, number):
        if number == 2:
            result = "prime"

        if number % 2 == 0:
            result = "not prime"

        highesttestnum = number ** 0.5 + 1
        count = 3
        while count <= highesttestnum:
            if number % count == 0:
                result = "not prime"
            count += 2

            result= "prime"

        return result

if __name__ == '__main__':
    obj = PrimeTester()

When ever you call a method inside another use 'self' which refers to the current object. Please read python doc. http://docs.python.org/2/tutorial/classes.html .

While printing you have to convert your integer value to string for concatenating them.
And try to return something from method instead of printing that is more pythonic.

Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43