【问题标题】:Don't understand why if statement fails. Function to find prime number [duplicate]不明白为什么 if 语句失败。查找素数的函数[重复]
【发布时间】:2015-11-04 08:30:29
【问题描述】:
def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        for i in range(2, x):
            if x % i == 0:
                return False
            else:
                return True

这不适用于数字 9,它返回 true。 请用基本术语解释一下。

【问题讨论】:

  • 您在第一次循环迭代中决定是否为素数。 return true; 必须在循环结束时调用。

标签: python


【解决方案1】:

您必须删除for 循环中的else 条件。例如:对于输入:9 当执行进入for 循环时,检查的条件是9 % 2 == 0。因为它是 False,所以执行将继续到 else 部分,并将返回值 True。它没有做的是继续检查与其他数字的可分性。因此,如果条件不为真,它应该简单地继续检查与其他数字的可分性。

代码:

def is_prime(x):
    if x < 2:
        return False
    elif x == 2: 
        return True 
    else:
        for i in range(2, x):
            if x % i == 0:
                return False
        return True

【讨论】:

猜你喜欢
  • 2013-01-25
  • 2014-01-16
  • 2020-11-17
  • 2021-04-24
  • 2017-01-26
  • 1970-01-01
  • 2016-04-14
  • 2015-02-11
  • 1970-01-01
相关资源
最近更新 更多