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)) 
3
  • 3
    Where do you initialize an instance of PrimeTester? Commented Feb 7, 2014 at 3:56
  • 2
    More important: Why do you use a class here? Commented Feb 7, 2014 at 9:30
  • I'd suggest if you going to use a class here, that you pass the number_to_test as an argument to the constructor. Commented Feb 7, 2014 at 15:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.