[Tutor] help with prime number program

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Oct 30 18:45:41 CET 2005



> I am trying to write a program that will figure out if a number is prime
> or not. Currently this is the code that I have:

[code cut]

Hi Andrade1,

As in your other previous homework programs, you seem to have some trouble
with control flow.  Have you considered talking with your professor or
teaching assistant about this?


> import math
>
> def main():
>     number=input("Please enter a positive whole number greater than 2: ")
>     for value in range(2, number-math.sqrt):
>         if number % value == 0:
>             print number, "is not prime"
>             exit
>     print number, "is prime"
>
> main()
>
> my problem is that the output prints both statements whether the number
> is prime or not.


The block of code:

######
    for value in range(2, number-math.sqrt):
        if number % value == 0:
            print number, "is not prime"
            exit
######

has two issues.

    1.  What is 'exit'?

    2.  What is 'number - math.sqrt'?

Instead of 'exit', you may be looking for the 'return' statement instead.


Good luck to you.



More information about the Tutor mailing list