I'm a beginning programmer in python and have a question about my code I'm writing:
number = int(input("Enter a random number: "))
for num in range(1, number + 1) :
for i in range(2, num) :
if (num % i) == 0 :
break
else :
print(num)
break
When I run this program I also get 9, 15 21 as output. But these are not prime numbers. What is wrong with my code?
Thanks!
With if (num % i) == 0:
you go to the else
block for every num
, which is not a multiply of 2, as you start i
with 2, thus printing num
. I got all odd numbers printed with your code.
You can use something like this:
number = int(input("Enter a random number: "))
for num in range(1, number + 1):
prime = True
for i in range(2, num):
if (num % i) == 0:
prime = False
break
if prime:
print(num)
It sets prime
to False
when it encounters a divisor without rest.
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