该程序假设找到1000个素数并将它们打包成一个列表
以下是代码:
num = raw_input('enter a starting point')
primes = [2]
num = int(num)
def prime_count(num):
if num % 2 == 0: #supposed to check if the number is divided by 2 evenly
num = num +1 #if it is, then add 1 to that number and check again
return num
elif num % num == 0:
primes.append(num) #supposed to add that prime to a list
num = num + 1 #add 1 and check again
return num
while len(primes) <= 999:
prime_count(num)
那么当我运行它时会发生什么: 它问我raw_input然后根据我选择的输入去做各种事情:
我做错了什么?
更新: 我修复了它,但是当我运行它时,我得到一个错误(TypeError:不支持的操作数类型为%:&#39; NoneType&#39;和&#39; int&#39;)< / p>
number = raw_input('enter a starting point')
primes = [2]
number = int(number)
def prime_count(x):
if x % 2 == 0: #supposed to check if the number is divided by 2 evenly
number = x +1 #if it is, then add 1 to that number and check again
return number
else:
for i in range(3, x-1):
if x % i == 0:
primes.append(x) #supposed to add that prime to a list
number = x + 1 #add 1 and check again
return number
while len(primes) <= 999:
number = prime_count(number)
答案 0 :(得分:0)
您永远不会使用prime_count的返回值。试试这个:
while len(primes) <= 999:
num = prime_count(num)
通过在num
内使用名称prime_count
作为参数(也是局部变量),以及作为全局变量,您已经设置了自我混淆。由于Python的变量范围规则,即使它们具有相同的名称,它们也是不同的变量。
此外,prime_count
(可能是无意中)利用primes
是全局变量的事实。由于您未为其分配,而只是调用方法(追加),因此代码无需使用global
关键字即可使用。
但是,您的算法甚至不正确。 if num % num == 0
说&#34;如果一个数字除以自身的余数为零&#34; ,总是为真。这个程序会找到很多&#34; primes&#34;那些不是素数。
真正的Python程序在全球范围内做的很少;你当前的代码只是要求混淆。我建议你从这个模板开始,并对现有的Python代码进行一些阅读。
def add_three(a_param):
a_local_var = 3 # This is *different* than the one in main!
# Changes to this variable will *not* affect
# identically-named variables in other functions
return a_local_var + a_param
def main():
a_local_var = 2
result = add_three(a_local_var)
print result # prints 5
if __name__ == '__main__':
main()