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 ?

Edward Sun
  • 183
  • 2
  • 12
  • 2
    range starts from 1, and target % num is always 0. – cs95 Jul 10 '17 at 20:56
  • What do you mean at all? Are you failing to call the methods? Can you get something as simple as the `hello world` working without your calculations and `if/else`s? – Davy M Jul 10 '17 at 20:56
  • Don't smash all your logic in one big monolithic function. Have ``is_prime(x)``, ``is_perfect_square(x)`` functions and apply them on a sequence. – Meitham Jul 10 '17 at 21:18

2 Answers2

3

Few things. The first is that you run num from 1 to target + 1. num % 1 is always 0, so you never print any primes.

Next, you do not reset your prime and perfSqr flags across iterations. Also, you'll need to move your print statements inside the outer loop, so they print every iteration.

This works as expected:

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')
cs95
  • 379,657
  • 97
  • 704
  • 746
1

1) Your indentation is off- it seems like you want the if block to be indented so it is inside the first for loop

2) You do not reset prime and perfSqr inside the first for loop, so once they are set they are never reset.

3) Your inner for loop range starts at 1, when it should start at 2, otherwise it seems makes all numbers prime.

Is this what you want?:

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()
Jason S
  • 129
  • 3