python3练习100题——014

这题卡了我一整天,然后还是看答案撸了一遍~

原题链接:http://www.runoob.com/python/python-exercise-example14.html

题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。

我的代码:

def fun():
    num=int(input("please input a number:"))
    if not isinstance(num,int) or num <0:
        print("it is not a correct number")
    elif num==1:
        print("%d=%d" %(num,num))
    else:
        while True:                #必须要while循环,质数可能有重复的. 这个条件是有问题的,跳不出去,应该改成while num!=1
            for i in range (2,num+1):         #保证i能取到num
                if num%i==0:
                    num=int(num/i)
                    if num==1:         #除到最后的一个质数,num就为1了   这样的条件语句很巧妙地处理了最后一个打出*的问题
                        print("%d" %i,end='')
                    else:
                        print("%d*" %i,end='')
                    break            #break的是第一个循环,while循环继续

思考:

学到了print('{}'.format(变量))的格式化输出方式~

另外循环一定要有出口!

猜你喜欢

转载自www.cnblogs.com/drifter/p/9125680.html