【问题标题】:Receiving a "TypeError: 'int' object is not callable" error when finding Primes?查找 Primes 时收到“TypeError:'int' object is not callable”错误?
【发布时间】:2021-07-08 03:14:14
【问题描述】:

我正在尝试编写一个程序来查找素数,这是我目前的代码

import math
import numpy 
PrimeList = (2)    #starting prime list at 2
for numbers in range(3,10001):    #beginning loop for primes from 3 to 10000
    i = 0
    PrimeList_flag = True
    while PrimeList(i) <= math.floor(math.sqrt(numbers)):    # checks number divisibility by any prime less than or equal to sqrt of number
        if numbers % prime(i)==0:
            PrimeList_flag = False    # sets flag to true if the last note is true
            break    #loop breaker
        i += 1   # for i greater than or equal to 1
    if PrimeList_flag ==True: 
        PrimeList.append(num)
print(PrimeList)

返回此错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-38-304e050286f5> in <module>
      5     j = 0
      6     PrimeList_flag = True
----> 7     while PrimeList(j) <= math.floor(math.sqrt(numbers)):    # checks number divisibility by any prime less than or equal to sqrt of number
      8         if numbers % prime(j)==0:
      9             PrimeList_flag = False    # sets flag to true if the last note is true

TypeError: 'int' object is not callable

我已经检查了与此相关的其他答案,关于在前面的代码行中将变量分配给整数,但我在迄今为止编写的任何代码中都没有看到这一点。我还有什么遗漏的吗?

提前致谢!

【问题讨论】:

  • "TypeError: 'int' object is not callable" 你认为PrimeList(i) 是什么意思? “我已经检查了与此相关的其他答案,关于在前面的代码行中将变量分配给整数”你期望PrimeList = (2) 是什么意思?
  • PrimeList = (2) 应该是PrimeList = [2]
  • 如果这些不是简单的拼写错误,那么您有一个或多个基本误解应该通过遵循教程来解决,而不是通过尝试提出自己的项目并获得帮助。

标签: python object integer callable


【解决方案1】:

首先,python 中的列表是用方括号声明的——你所拥有的是一个简单的整数。

其次,对于您的特定问题,您必须使用方括号进行索引。括号用于调用可调用对象(函数)。所以你需要使用

PrimeList[i]

另外,prime 是从哪里来的?这是你导入的函数吗?

【讨论】:

  • 其实(2)不是一个元组;它只是整数2。创建一个元组需要逗号,例如(2,)
  • 谢谢@gshpychka 和Karl,问题是缺少括号。卡尔,你说得对,我确实需要花更多时间了解基础知识。 gshpychka,prime 应该是 PrimeList
  • 如果您觉得以上答案回答了您的问题,请考虑接受。
猜你喜欢
  • 2022-11-20
  • 2021-10-22
  • 1970-01-01
  • 2014-11-25
  • 1970-01-01
  • 2017-04-06
  • 2013-03-30
  • 2016-03-25
  • 2021-09-15
相关资源
最近更新 更多