python code writing practice
时间: 2024-05-08 18:21:46 浏览: 67
Sure, here's a simple code to calculate the factorial of a number using recursion in Python:
```
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num-1)
# Test the function
num = 5
print("Factorial of", num, "is", factorial(num))
```
In this code, we define a function `factorial` that takes a number as input and returns its factorial. We use recursion to calculate the factorial - if the number is 0, we return 1 (since 0! = 1), otherwise we call the `factorial` function recursively for `num-1` and multiply the result with `num`.
We then test the function by calling it with the number 5 and printing the result. You can try running this code and testing the function with different inputs.
阅读全文