往期内容回顾——函数的定义与调用
在Python中,函数是这样定义的:
def helloPrint(name): print(‘hello’+name)
Python函数定义的基本语法如下:
def name(parameter1, parameter2, . . .): Body
调用fact函数即可得到阶乘值了:
>>> def fact(n): ... """ Return the factorial of the given number. """ ⇽--- ❶ ... r = 1 ... while n > 0: ... r = r * n ... n = n - 1 ... return r ⇽--- ❶ ...
虽然Python函数都带有返回值,但是否使用这个返回值则由写代码的人决定:
>>> fact(4) ⇽--- ❶ 24 ⇽--- ❷ >>> x = fact(4) ⇽--- ❸ >>> x 24 >>>
实例讲解:
#在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
#例如计算阶乘n! = 1 x 2 x 3 x ... x n
def fact(n):
if n == 1:
return n
else:
return n * fact(n-1)
print(fact(5)) #120大家现在应该清楚关于fact函数是如何使用了吧,结合基础的函数知识,以及实际的操作,相信便于大家理解。学会以后,记得运用在实际操作上哦~









