python - 为什么我的 Python 函数在控制台中可以工作,但在代码中调用时却不能工作?

标签 python python-3.x

我正在尝试通过解决 Project Euler 网站上的问题来学习 Python。我确切地知道我想要我的代码做什么,并且我的方法在纸上有效,但我无法使代码工作。

GitHub 链接:https://github.com/albyr/euler-python/blob/master/euler3.py

我创建了两个函数,一个用于计算目标数字的因数,另一个用于检查给定数字是否为质数。

# Function that finds all the factors of a given number
def findfactors(n):
    # for i in range(1,int(sqrt(n)+1)):
    for i in range(1,n+1):
        if n/i == int(n/i):
            factors.append(i)

# Function that checks if a number is prime
def checkprime(n):
    # Trial division
    for i in range(2,int(sqrt(n)+1)):
        if n/i == int(n/i):
            # Number gives a remainder upon division and therefore is not prime
            isprime = False
            break
        else:
            isprime = True
    if isprime == True:
        return True
    elif isprime == False:
        return False

我确信对于专家来说,这些代码看起来很糟糕。但如果我使用 Python shell,它就可以工作:

>>> checkprime(9)
False
>>> checkprime(79)
True
>>> checkprime(factors[3])
True

但是当我用 F5 运行程序时,我得到:

Traceback (most recent call last):
  File "/home/alby/euler-python/euler3.py", line 45, in <module>
    checkprime(factors[i])
  File "/home/alby/euler-python/euler3.py", line 32, in checkprime
    if isprime == True:
UnboundLocalError: local variable 'isprime' referenced before assignment

如果我使用硬编码数字(例如 checkprime(77))从程序内调用 checkprime 函数,我根本不会得到任何输出。我确信这是关于 Python 工作方式的一些我不理解的基本内容,但我一生都无法弄清楚是什么。

有什么建议吗?

最佳答案

在您的 Github 代码中,我们可以看到您正在尝试调用 checkprime(1)(在最后一个循环的第一次迭代中)。

# Check each factor to see if it is prime or compound
for i in range(0,len(factors)):
    print (factors[i])
    # Why can't I call checkprime here, like this? It works in the console.
    checkprime(factors[i])

但是看看你的代码:

def checkprime(n):
    # Trial division
    for i in range(2,int(sqrt(n)+1)):
        if n/i == int(n/i):
            # Number gives a remainder upon division and therefore is not prime
            isprime = False
            break
        else:
            isprime = True

如果n = 1,则range(2, int(sqrt(1)+1))range(2,2) 它是空的...所以 isprime 永远不会被设置,因为循环体永远不会运行。

请记住,range() 的参数是一个半开区间 - range(x,y) 是“整数”从 x 开始并在 y 之前结束”。因此 range(2,3) = [2]range(2,2) = []

这里的另一个问题是 findfactors() 返回 1 作为第一个因素 - 这可能不是您想要的:

def findfactors(n):
    # for i in range(1,int(sqrt(n)+1)):
    for i in range(1,n+1):

对于质因数分解检查,您可能希望从 2 开始,而不是 1(因为所有内容都可以被 1 整除)。


此外,这段代码是多余的:

if isprime == True:
        return True
    elif isprime == False:
        return False

你真的可以把它写成...

return isprime

或者您可以做得更好,从一开始就不使用 isprime - 只需将 isprime = True 替换为 return Trueisprime = Falsereturn False

最后,int(n/i) 的简写是 n//i - Python 的 // 运算符进行整数除法。

关于python - 为什么我的 Python 函数在控制台中可以工作,但在代码中调用时却不能工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11476071/

相关文章:

python - RIDE-1.5.2.1 无法导入所有基础库

Python 可以导入未安装的模块

python - 在 OSX 上安装多个版本的 python 包

python - 合并和比较

python - 在 MacOS big sur 上安装 jupyterlab/jupyter notebook 时出错

python - Django模型: sum in def

python - Column DataFrame Python 中的计算器数组

python - OpenERP-v7 : Add custom field to delivery order from sale order

python - 检查 Python 字典中列表中的重复元素

python - 如何按名称取消异步任务?