You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 return statement. In Python, any function without a defined return value automatically returns None.
  • Since you're wrapping the function call in print(), you end up printing both the message from inside the function and the default None the 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:05:38