Hi im writing a program that returns whether an inputted number is prime or not, but Im kind of stuck...

import math
def listfactors(n): # defining the function
    l = []
    for i in range (1, int(math.sqrt(n))+1):               
        if float(n)/float(i) == int(float(n)/float(i)):
    return l              

primeNum = int(raw_input("Enter number here:"))
if listfactors(primeNum) =
    print "prime"

Now thats what I have so far but its not working and I was wondering if anyone could help point out my mistake and help me fix the last 2 lines.
Thank you :)

8 Years
Discussion Span
Last Post by Progressivism

If you want to determine if a number is prime or not, you should return True (if prime) or False (if not prime). Use the modulo operator to determine if the entered number is divisible by loop variable i.

if not n%i:

If the statement evaluates True, return False. If the loop continues until it finishes, return True because the number must be prime.

The name of your function implies you have a different purpose. A better description would be is_prime:

if is_prime(primeNum):
    print "The number is prime."
   print "Nope."

Your last 2 lines would be modified thusly

primeNum = int(raw_input("Enter number here:"))
prime_list = listfactors(primeNum)  ## your function returns a list
for prime in prime_list:
    print "prime =", prime

Also, a second for using modulo or divmod. Your function compares integers and floats and you will be comparing numbers like int=1, and float=0.99999 because of the nature of using floats which will always test false. Hopefully you are only testing integers for "primeness" and so should work with integers only. Finally, it is bad form to use "i", "l", or "o" as single letter variables, as they look too much like numbers.


I too suggest the use of % to check for zero remainder, avoiding floating point in this problem.

A nit on operators: when you want integer-style division, discarding any remainder, the proper operator is // not / . As in: l.append(n//i) . In this particular case you already know the results are exact so no harm done, but it's good programming practice since it makes your intentions clear.


primeNum = int(raw_input("Enter number here:"))
print listfactors(primeNum)

This thread was dead AND solved long ago. Plus, your post helped with nothing.
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.