### Python编程帮助

``````#!/usr/bin/env python
import math

def primeTest(isPrime):
print('    {0}=testnum'.format(testnum))
if testnum%2 == 0 and testnum != 2: #if divisible by 2 and not 2
isPrime = False
print('{0} a'.format(isPrime))
print('a')
else:
numroot = round(math.sqrt(testnum))
i = 2
while i <= numroot:
if testnum%i == 0:
isPrime = False
i+=1
print('b')

global testnum
global isPrime
testnum=2
numPrimesSoFar=0
reqPrimes=int(input('How many primes would you like? \n'))
while numPrimesSoFar < reqPrimes:
isPrime=True
primeTest(isPrime)
print(isPrime)
if isPrime:
print('    {0}'.format(isPrime))
print('    {0}'.format(testnum))
numPrimesSoFar+=1
testnum+=1
``````

（抱歉格式化我不确定为什么它不正常，但假设我的标签格式正确） 现在输出：

``````    How many primes would you like?
4
2=testnum
b
True
True
2
3=testnum
b
True
True
3
4=testnum
False a
a
True
True
4
5=testnum
b
True
True
5
``````

#### 4 个答案:

`global isPrime`需要位于您分配给`isPrime`的函数内。

``````def primeTest():
global isPrime
isPrime = False

isPrime = True
print isPrime # returns True
primeTest()
print isPrime # returns False
``````

``````def primeTest(testnum):
... do your calculations here, set a variable ret_val to True or False ...
return ret_val
``````

global foo意味着，在这个范围内，让我说foo引用从这个范围之外可访问的foo，并在此范围关闭后持久化。这并不意味着，让所有名为foo的变量无处不在并永远引用这个foo。