python中for循环求素数,素数python for循环

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 range(2,n):

if n%i == 0:

print(False)

print(True)

when I enter a prime number it works but when I enter a non prime number it doesn't work.

Example:

>>>

Enter a number: 12

False

False

False

False

True

>>>

please help!

解决方案

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.

你可能感兴趣的:(python中for循环求素数)