下面程序的输出是 。 def factorial(n): match n: case 0 | 1: return 1 case _: return n * factorial(n - 1) print(factorial(5))
时间: 2024-02-14 19:35:55 浏览: 24
这段程序的输出是 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): match n: case 0 | 1: return 1 case _: return n * factorial(n - 1) print(factorial(5))
这段Python 3代码使用了新的模式匹配语法,输出结果是`120`,即$5! = 5 * 4 * 3 * 2 * 1 = 120$。
`factorial()`函数实现了计算阶乘的功能,使用了Python 3.10中新增的`match`语句进行模式匹配。当输入为0或1时,直接返回1;否则递归计算$n*(n-1)!$。在本例中,`factorial(5)`返回的结果为$5*4*3*2*1=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.
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)