Python解决阶乘计算问题

最近面试遇到的几个问题,记录。

1. 问题如下

Python解决阶乘计算问题_第1张图片

代码如下。

对于该题的测试用例设计需要考虑全面。

def FirstFactorial(num):
    if num >18:
        print("You should input a number between 1 and 18")
        num2 = int(raw_input("input an integer number in range 1-18:"))
        cal(num2)
        print("%d factorials is %d" % (num2, firstNum))
    elif num == 0:
        cal(num)
    elif num < 0:
        print("Minus No Factorials")
    else:
        cal(num)
        print("%d factorials is %d" % (num, firstNum))
def cal(recNum):
    global firstNum
    for i in range(1, recNum + 1):
        firstNum = firstNum * i
    return firstNum

if __name__=='__main__':
    # input always be an integer
    for j in range(2):
        try:
            orginalNum = int(raw_input("input an integer number in range 1-18:"))
        except Exception as e:
            print("It's not Integer", e)
        else:
            firstNum = 1
            FirstFactorial(orginalNum)

你可能感兴趣的:(Python)