#!/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
好的...当我将它设置为false时,为什么Prime仍然为true?
编辑:好的...那是你们在说什么?
最佳答案
global isPrime
必须位于分配给isPrime
的函数中。
关于python - Python编程帮助,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1769278/