如何找到root ** power = number并打印出“找不到号码”的消息?

时间:2013-06-11 03:31:57

标签: python

我想打印根和电源, 其中0 < 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"消息。请帮忙!

1 个答案:

答案 0 :(得分: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"