Python质数判断函数问题:非质数场景返回None求助
None的问题 Hey, let's break down why you're seeing that extra None pop up when inputting a non-prime number.
问题根源
The issue boils down to how Python handles function return values. Let's take a closer look at your code:
def is_prime(): your_guess = int(input("Choose a number to find out if it's prime...")) div = 2 is_prime = True while div < your_guess: if your_guess % div == 0: is_prime = False print ("The Number is not Prime") break div += 1 else: if is_prime == True: return ("The number is Prime!") print (is_prime())
Here's what's happening with non-prime inputs:
- The loop finds a valid divisor, prints "The Number is not Prime", then breaks out of the loop.
- After breaking, the function never hits an explicit
returnstatement. In Python, any function without a defined return value automatically returnsNone. - Since you're wrapping the function call in
print(), you end up printing both the message from inside the function and the defaultNonethe function sends back.
For prime numbers, the loop completes without hitting break, so it enters the else block and returns the prime confirmation string — that's why you don't see None in that case.
两种修复方案
方案1:统一用return返回结果(推荐)
Instead of printing inside the function, return the message for both prime and non-prime cases, then print the function's output once outside. This keeps your code consistent and easier to maintain:
def is_prime(): your_guess = int(input("Choose a number to find out if it's prime...")) div = 2 while div < your_guess: if your_guess % div == 0: return "The Number is not Prime" div += 1 # If we exit the loop without returning, the number is prime return "The number is Prime!" print(is_prime())
方案2:在函数内部处理所有打印,不返回值
If you prefer to print directly inside the function, just remove the print() around the function call. Since the function doesn't need to return anything, calling it alone will execute the prints without outputting None:
def is_prime(): your_guess = int(input("Choose a number to find out if it's prime...")) div = 2 is_prime = True while div < your_guess: if your_guess % div == 0: is_prime = False print("The Number is not Prime") break div += 1 else: print("The number is Prime!") # Just call the function directly, no print() needed is_prime()
Either fix will eliminate that annoying extra None!
内容的提问来源于stack exchange,提问作者Leo C

