user12114101
user12114101

Reputation:

what loop does this break break?

n = int(input('Input an integer: '))
modn = abs(n)
power = 2
while power < 6:
    root = 0
    while root ** power < modn :
        root = root + 1
    if root ** power == modn and n < 0 :
        root = -root
        print(root, 'raised to', power, 'is', n)

        break #<---------(this break) 
    elif root ** power == modn and n > 0 :
        print(root, 'raised to', power, 'is', n)
        break
    else : power = power + 1

    if power == 6 :
        print('No values of power and root exist for this input.')

I wrote down this code for the finger exercise in Introduction to Computation and Programming Using Python, by John Guttag, and so far it works good. My question is which loop is being stopped by the first break, is it the while power < 6 or while root ** power < modn :. My guess is the first while loop but shouldn't it be the second?

Upvotes: 1

Views: 38

Answers (2)

I'll be the first loop because of the indentation of your code, you actually do the break outside of the loop i think what you are trying to achieve is

n = int(input('Input an integer: '))
modn = abs(n)
power = 2
while power < 6:
    root = 0
    while root ** power < modn :
        root = root + 1
        if root ** power == modn and n < 0 :
            root = -root
            print(root, 'raised to', power, 'is', n)

            break #<---------(this break) 
        elif root ** power == modn and n > 0 :
            print(root, 'raised to', power, 'is', n)
            break
        else : power = power + 1

if power == 6 :
    print('No values of power and root exist for this input.')

Upvotes: 1

Siong Thye Goh
Siong Thye Goh

Reputation: 3586

It is the first while loop.

The second while loop only consists of

while root ** power < modn :
    root = root + 1

It doesn't contain a break statement.

Upvotes: 1

Related Questions