我必须编写一个程序,用户在其中输入数字,然后检查它是否为素数,但是无论您输入什么,它都会说素数。如何解决此代码?
def is_prime(n):
if n < 2: return False
for x in range(2, int(n**0.5) + 1):
if n % x == 0:
return False
return True
def main():
keep_going='y'
while keep_going=='y':
n=int(input("Please enter a number to see if it's prime: "))
is_prime(n)
if True:
print("It's prime")
if False:
print("it's not prime")
keep_going=input("would you like to see if another number is prime? (y/n):")
main()
答案 0 :(得分:1)
这样做
while keep_going=='y':
n=int(input("Please enter a number to see if it's prime: "))
if is_prime(n):
print("It's prime")
else:
print("it's not prime")
keep_going=input("would you like to see if another number is prime? (y/n):")
答案 1 :(得分:1)
您没有在任何地方分配is_prime(n)
的返回值,也没有测试该返回值。 if True:
是无条件执行。 if False:
是无条件不执行。
相反,您想测试is_prime(n)
:
if is_prime(n):
...
else:
...
或
prime = is_prime(n)
if prime:
...
else:
...
好消息是-您的is_prime
函数正确,并且确实返回了非质数的False
:)
答案 2 :(得分:0)
尝试一下
def is_prime(n):
if n < 2:
return False
elif n % (n // 2) == 0:
return True
else:
return False
def main():
keep_going = 'y'
while keep_going == 'y':
n = int(input("Please enter a number to see if it's prime: "))
if is_prime(n):
print("It's prime")
else:
print("it's not prime")
keep_going = input("would you like to see if another number is prime?(y/n):")
main()