Skip to content Skip to sidebar Skip to footer

Prime Number Python For Loops

Question: A program that take a positive integer n as input and returns True if n is a prime number, otherwise returns False. My Answer: n = int(input('Enter a number: ')) for i in

Solution 1:

You can break and use else:

n = int(input("Enter a number: "))
for i inrange(2, n):
    if n % i == 0:
        print(False)
        breakelse: 
    print(True)

True will only be printed if the loop completes fully i.e no n % i was equal to 0.

Solution 2:

Your code always prints True at the end, and prints a number of Falses before that. Instead, you should have a variable (isPrime?) that gets initialized to True and gets set to False when you find it is divisible by something. Then print that variable at the end.

Solution 3:

You're just printing each intermediate value, if you use return in a function it works fine

defprime(n):
    for i inrange(2, n):
        if n%i == 0:
            returnFalsereturnTrue>>> prime(5)
True>>> prime(12)
False

Solution 4:

You could use the for-else clause here. Also, you don't need to go beyond the square root of n:

import math

for i in range(2, int(math.sqrt(n))):
    if n % i == 0:
        print"False"breakelse:
    print"True"

Solution 5:

There's a lot of different ways to fix your code, but all of them hinge on the fact that you should be breaking out of that loop if you find a divisor (ie if n%i == 0)

Usually, you'd have a boolean value storing whether or not you've found a divisor, but python lets you do the following

n = int(input("Enter a number: "))
for i inrange(2,n):
    if n%i == 0:
        print(False)
        breakelse:
    #else statement only happens if you don't break out of the loopprint(True)

Post a Comment for "Prime Number Python For Loops"