I feel compelled to point out that your code works as long as you enter a number less than 11^2 = 121 (it would mistakenly identify 121 as prime).
The way you've written it is OK, but it doesn't really take advantage of the stronger features of Python. Let's look at the code:
x=0
y = raw_input("""Up to what number would you like to locate primes?: """)
for i in range(int(y)):
x = x + 1
if x%2 and x%3 and x%5 and x%7:
print x, '--> PRIME'
elif x==2 or x==3 or x==5 or x==7:
print x, '--> PRIME'
elif x==1:
print x
else:
print x
In Python, for i in range(int(y))
will set i
to 0, 1, 2, ..., y-1. So, you don't need a separate x
variable to keep track of the value:
y = raw_input("""Up to what number would you like to locate primes?: """)
for x in range(int(y)):
if x%2 and x%3 and x%5 and x%7:
print x, '--> PRIME'
In Python, you can use in
to quickly test equality against several choices (a special case of testing container membership), so x==2 or x==3 or x==5 or x==7
can be rewritten as x in (2, 3, 5, 7)
.
Now, if you want to count the number of primes, let's add a counter:
num_primes = 0
y = raw_input("""Up to what number would you like to locate primes?: """)
for x in range(int(y)):
if x == 1:
# 1 actually passes the modulo tests and would be considered prime in the original code
print x
elif (x%2 and x%3 and x%5 and x%7) or x in (2, 3, 5, 7):
num_primes += 1 # this increments num_primes by 1
print x, '--> PRIME'
else:
print x
And finally print it out with a nice formatted message:
print 'There are {} primes between 0 and {}'.format(num_primes, y)
Ta-da!