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, n
I am assuming the random number is the range you want the numbers to be within.
I found that the variable i is always equal to 2 in your code.This destroys the purpose of having a second for loop
Prime numbers are numbers that cannot be divisible by 2, 3 or 7, excluding 2, 3 or 7!
With this knowledge I adapted your code to show the true prime numbers.
solution
number = int(input("Enter a random number: "))
for num in range(2,number +1) :
printnum = True
if num == 2:
printnum = True
elif num == 3:
printnum = True
elif num == 7:
printnum = True
elif num % 2 == 0:
printnum = False
elif num % 3 == 0:
printnum = False
elif num % 7 == 0:
printnum = False
if printnum == True:
print(num)
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.
This is my method to generate first ten prime numbers with no imports, just simple code with components we are learning on college. I save those numbers into list.
def main():
listaPrim = []
broj = 0
while len(listaPrim) != 10:
broj+= 1
brojac = 0
for i in range(1,100):
if broj % i == 0:
brojac += 1
if brojac == 2:
listaPrim.append(broj)
print(listaPrim)
if __name__=='__main__':
main()
the trouble is in your else: statement which has to run outside of the first loop. I recommend the following:
def isprime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
for num in range(1, number + 1) :
if isprime(num):
print num
Your problem
The else statement that you put inside the for loop means that if that number(num) is divisible by this current no represented by i, return true considering it as a prime which IS NOT CORRECT.
Suggestion
Your outer loop starts with 1 which should change to 2, as 1 is not a prime number
Solution
def fun(number):
#Not counting 1 in the sequence as its not prime
for num in range(2, number + 1) :
isPrime = True
for i in range(2, num) :
if (num % i) == 0 :
isPrime = False
break
if isPrime:
print num
fun(10)
Output
1
2
3
5
7