Write a python function proddigits() that inputs a positive integer number and returns the product of digits of that number. For example, if the input is 422, the function should return 16 (which is equal to 4×2×2 ).
时间: 2023-12-06 14:39:41 浏览: 111
python实现将字符串中的数字提取出来然后求和
Here's one way to write the `proddigits()` function in Python:
```python
def proddigits(num):
"""Returns the product of the digits in a positive integer number."""
product = 1 # start with a product of 1
while num > 0:
digit = num % 10 # extract the rightmost digit
product *= digit # multiply the product by the digit
num //= 10 # remove the rightmost digit from the number
return product
```
You can call this function with a positive integer argument to get the product of its digits:
```python
print(proddigits(422)) # Output: 16
print(proddigits(12345)) # Output: 120
print(proddigits(987654321)) # Output: 362880
```
The function works by iterating over the digits of the input number using a while loop. In each iteration, it extracts the rightmost digit using the modulo operator (`%`) and multiplies the product by that digit. Then it removes the rightmost digit from the number using integer division (`//`). The loop continues until there are no more digits left in the number. Finally, the function returns the product of all the digits.
阅读全文