Reputation: 5
Problem is that for every value it finds it follows if-statement and either print("Prime")
or
print("Not prime")
, What I want is for it to search the list completely, if the value is found, print("Not prime")
once, not for each value it finds, and if it's not found, I want it to print("Prime")
once.
Code below:
inp1 = int(input("The following: "))
for i in range(2, inp1):
rest = inp1 % i
liste = [rest]
if 0 in liste:
print("Not prime")
else:
print("Prime")
Upvotes: 0
Views: 43
Reputation: 531355
You don't need a list. If inp1 % i
is 0, the number is not prime; you can break out of the loop immediately. If the inp1 % i
is not 0, the number may be prime; you have to stay in the loop and check the next value.
One often overlooked feature of a for
loop is that it can take an else
clause itself. The else
clause executes if the loop exits "naturally", by exhausting its iterator. If you exit the loop with break
, the else
does not execute.
for i in range(2, inp1):
if inp1 % i == 0:
print("Not prime")
break
else:
print("Prime")
Prime
will only be printed once, and only if the break
statement is not used.
The same algorithm can be implemented with any
:
if any(inp1 % i == 0 for i in range(2, inp1):
print("Not prime")
else:
print("Prime")
In this case, any
only returns True
if one of the conditions is true, after which it does not check any additional conditions.
Upvotes: 1