I started learning Python today, and I came up with the idea of creating a program that prints all the prime numbers from 0 to 10 000. I managed to make my program print out all primes until 251, at which point it stops printing out numbers. Why does it do this?
Here is the code:
for numberToCheck in range(2,10000): divider = 2 while numberToCheck > divider: if numberToCheck % divider is 0: break else: divider += 1 if numberToCheck is divider: print(numberToCheck, "is a prime number.")
The problem is that you are using is
instead of ==
. The is
operator performs object identity comparison, which "happens to work" for all numbers below 256
due to implementation details. 251
is the biggest prime below 256 (check here, next prime is 257) and after that the is
returns False
:
>>> 254 + 1 is 255 True >>> 255 + 1 is 256 True >>> 256 + 1 is 257 False
The equality operator is ==
:
>>> 254 + 1 == 255 True >>> 255 + 1 == 256 True >>> 256 + 1 == 257 True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With