pythonfor-looplogic

How can I use a for loop to check whether any value matches a condition?


I was tasked with writing a program that asks for a positive integer n as input and outputs True if n is a prime number and False otherwise.

I came up with this code:

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

However, it only works properly for prime numbers. If I try a composite number, I get multiple False outputs followed by True. For example, with input 12 I see

False
False
False
False
True

How can I make it so that after I find out that the number is composite, nothing more is printed after False?


Solution

  • You can break and use else:

    n = int(input("Enter a number: "))
    for i in range(2, n):
        if n % i == 0:
            print(False)
            break
    else: 
        print(True)
    

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