0

我想打印出root和power,where0 < power < 6root^power=number(由用户输入),否则它应该打印出"no such a number"消息

这是我的工作:

number=int(raw_input("enter the number:"))
power=2
root=0

while power<6:
    while root**power < abs(number):
        root=root+1
        if root**power==abs(number):
            if number<0:
                print 'root=',-root
            else:
                print 'root=',root
            print 'power=',power

    power=power+1
    root=0

它运作良好,但我不知道在哪里放置"no such a number"消息。请帮忙!

4

1 回答 1

0

您可以使用 for-else/while-else:

number=int(raw_input("enter the number:"))
power=2
root=0

for power in range(6):
    while root**power < abs(number):
        root=root+1
        if root**power == abs(number):
            if number < 0:
                if power % 2 == 1:  # Note a change here, 
                                    # you won't get negative number with even power
                    root = -root
                    print 'root=',root
                    print 'power=',power
                    break
            else:
                print 'root=',root
                print 'power=',power
                break
    if root**power == number:  # Make sure we break "for" too
        break
else:
    print "No such number"
于 2013-06-11T03:42:07.780 回答