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.')
我在John Guttag撰写的《使用Python进行计算和编程入门》中写下了用于手指锻炼的代码,到目前为止,它的工作效果很好。
我的问题是第一个中断正在停止哪个循环,是否是while power < 6
或while root ** power < modn :
。我的猜测是第一个while循环,但不应该是第二个吗?
答案 0 :(得分:1)
这是第一个while循环。
第二个while循环仅包含
while root ** power < modn :
root = root + 1
它不包含break语句。
答案 1 :(得分:1)
由于您的代码缩进,我将成为第一个循环,您实际上在循环之外进行了中断,我认为您要实现的目标是
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.')