1

I am trying to write my own prime number and perfect square checker using Python, The function should print 'Foo' if this is a prime number, print 'Bar' if this is a perfect square, print 'FooBar' if it is neither here is my code:

def FooBar():
    prime = True
    perfSqr = False
    for target in range(100,100001):
        for num in range(1,target+1):
            if target % num == 0 and num != target:
                prime = False

            if target // num == num and target % num == 0:
                perfSqr = True

    if prime is True:
        print 'Foo'
    elif perfSqr is True:
        print 'Bar'
    else:
        print 'FooBar'

if __name__ == '__main__':
    FooBar()

somehow, I cannot get it running at all, can anyone give me some hint ?

4

2 回答 2

3

一些事情。第一个是你num1target + 1num % 1始终为 0,因此您永远不会打印任何素数。

接下来,您不要在迭代中重置您的primeperfSqr标志。此外,您需要将打印语句移动到外部循环内,以便它们打印每次迭代。

这按预期工作:

def FooBar():
    for target in range(100, 100001):
        prime = True
        perfSqr = False
        for num in range(2, target + 1):
            if target % num == 0 and num != target :
                prime = False

            if target // num == num and target % num == 0:
                perfSqr = True

        if prime or perfSqr:
            print(num, end=', ')
            if prime:
                print('Foo', end=', ')
            elif perfSqr:
                print('Bar', end=' ')
            print('\n')
于 2017-07-10T21:04:13.813 回答
1

1)您的缩进已关闭-似乎您希望 if 块缩进,因此它位于第一个 for 循环内

2)您不会在第一个 for 循环内重置 prime 和 perfSqr,因此一旦设置它们就永远不会重置。

3)您的内部 for 循环范围从 1 开始,应该从 2 开始,否则它似乎使所有数字都成为素数。

这是你想要的吗?:

def FooBar():
for target in range(100,100001):
    prime = True
    perfSqr = False
    for num in range(2,target+1):
        if target % num == 0 and num != target:
            prime = False

        if target // num == num:
            perfSqr = True

    if prime is True:
        print 'Foo'
    elif perfSqr is True:
        print 'Bar'
    else:
        print 'FooBar'



if __name__ == '__main__':
    FooBar()
于 2017-07-10T21:05:44.223 回答