Problem with returning prime number in a simple calculation program

Bjoern Schliessmann usenet-mail-0306.20.chr0n0ss at spamgourmet.com
Sun Mar 4 00:46:22 CET 2007


QHorizon at gmail.com wrote:
> [reformatted indentation]
> def prime():
>     num = input("Number ")
>     i = num - 1
>     divcounter = 0
>     while i > 1:
>         if num % i != 0
>             divcounter += 1 
>             i -= 1
>     if divcounter == num - 2:
>         print num, "is a prime number"
>     else:
>         print num, "is not a prime number"
> [...]
> As it says in the title, I'm having trouble with the prime number
> function.  It will print the sentence if the number is prime, but
> it if isn't, the program goes into a state in the terminal where
> the program never ends and you can just keep on typing.  

Sure thing. You designed the function to behave this way.

Look at the while loop -- especially think what happens if 
(num % i == 0). i will never be decremented then and the function
will not terminate.

Try inserting print statements for debugging if you don't get what I
meant here.

> Maybe the else statement is ineffective?

No one can read your thoughts. In which way effective?

Regards,


Björn

-- 
BOFH excuse #86:

Runt packets




More information about the Python-list mailing list