def factorial(n): match n: case 0 | 1: return 1 case _: return n * factorial(n - 1) print(factorial(5))
时间: 2024-02-14 10:33:08 浏览: 46
这段代码定义了一个名为factorial的函数,使用了Python 3.10中的模式匹配语法来计算给定数的阶乘。函数接受一个整数n作为参数。
在函数内部,使用match语句对n进行匹配。如果n为0或1,则直接返回1。如果不是0或1,则返回n乘以(n-1)的阶乘,即递归调用自身计算(n-1)的阶乘,并将结果乘以n。
最后,调用了factorial函数计算5的阶乘,并打印出结果。因为5的阶乘等于5×4×3×2×1=120,所以代码输出的结果为120。
需要注意的是,这种模式匹配语法只在Python 3.10及以上版本中才能使用。在低于该版本的Python中,需要使用if-elif-else语句或其他方式实现相同的功能。
相关问题
下面程序的输出是 。 def factorial(n): match n: case 0 | 1: return 1 case _: return n * factorial(n - 1) print(factorial(5))
这段程序的输出是 120。程序中定义了一个计算阶乘的函数 factorial,使用了 Python 3.10 中引入的新特性 match-case。在 match-case 中,先匹配 n 是否为 0 或 1,若匹配成功,则直接返回 1;否则,使用通配符 _ 匹配任意值,并返回 n 与 factorial(n - 1) 的乘积。在程序的最后一行,调用了 factorial(5) 函数,计算出 5 的阶乘,结果为 120。因此,程序的输出就是 120。
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
This is a recursive function to calculate the factorial of a given number.
The factorial of a number is the product of all integers from 1 to that number. For example, the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
The function takes in a parameter 'n', which is the number whose factorial is to be calculated. If the number is 0, the function returns 1 (since the factorial of 0 is 1). Otherwise, it recursively calls itself with n-1 as the parameter and multiplies the result with n. This continues until n reaches 0, at which point the function returns the final result.