[Tutor] A problem
Glen Wheeler
gew75 at hotmail.com
Sun Jun 27 20:25:14 EDT 2004
Hi Ali,
The reason there is an error here is because of the seemingly innocent change
.. if a % x != 0 :
... print a
This prints a every single time there is another number x, where 2 <= x < a and x does not divide a. Obviously, this is not what you want -- for example, 3 does not divide 4, but 4 is not a prime!
In fact, this error persists in your first code example -- it tells me that 9 is prime? Perhaps some more thinking is in order ;).
Please note that there are many many better ways to accomplish this. A quick search with Google will turn up many prime number generators for your perusal, and hopefuly conversion to python :).
HTH,
Glen
----- Original Message -----
From: Ali Polatel
To: tutor at python.org
Sent: Monday, June 28, 2004 2:57 AM
Subject: [Tutor] A problem
I have just started to learn python...A problem has arised as I was trying to write a programme which lists the prime numbers up to a definite number. I had problems to create a definition for this... First what I have succeded to do is :
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, 'equals', x, '*', n/x
... break
... else:
... # loop fell through without finding a factor
... print n, 'is a prime number'
...
This lists the prime numbers up to 10 but when I try to create a definition with:
>>> def prime(n) :
... """ Hey dirty python! Show me the prime numbers!! """
... for a in range (2,n):
... for x in range (2,a):
... if a % x != 0 :
... print a
...
and then when I type prime(10) or any other number python gives wrong result.What is the right command?
My second question is when I achieve to create a definition for that how can i save it into a file so that the programme will just do this.I mean how to save something you do to an exe file or something similar...(I don't know the logic of python clearly yet)
------------------------------------------------------------------------------
Do you Yahoo!?
New and Improved Yahoo! Mail - Send 10MB messages!
------------------------------------------------------------------------------
_______________________________________________
Tutor maillist - Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040628/6381ff8e/attachment.html
More information about the Tutor
mailing list