in python, when uses print, how to control how many digits that a printed number show
时间: 2024-03-05 18:25:11 浏览: 28
You can use string formatting to control the number of digits that are displayed when you print a number in Python. One common way to do this is to use the `format()` method on a string. Here's an example:
```
x = 3.14159
print("The value of x is {:.2f}".format(x))
```
In this example, `"{:.2f}"` is a format string that tells Python to display `x` as a floating-point number with 2 decimal places. The `f` in `"{:.2f}"` specifies that the number should be formatted as a float.
Output:
```
The value of x is 3.14
```
You can replace the `2` in `"{:.2f}"` with any number to display a different number of decimal places.
相关问题
Write a program to print all digits of a given number by using a recursive function.
Here's the Python code to print all digits of a given number using a recursive function:
```
def print_digits(n):
if n < 10:
print(n)
else:
print_digits(n // 10)
print(n % 10)
# Example usage:
print_digits(12345) # Output: 1 2 3 4 5
```
In this code, the `print_digits` function takes an integer `n` as input. If `n` is less than 10, we simply print it. Otherwise, we first call the `print_digits` function recursively with `n // 10`, which gives us all the digits except for the last one. Then, we print the last digit by computing `n % 10`. This way, we print the digits in reverse order (from right to left).
Write a python function proddigits() that inputs a positive integer number and returns the product of digits of that number.
Here's a Python function `proddigits()` that takes a positive integer as input and returns the product of its digits:
```python
def proddigits(number):
product = 1
while number > 0:
digit = number % 10
product *= digit
number //= 10
return product
```
This function uses a while loop to iterate through each digit of the input number. It calculates the product of each digit by using the modulus operator (%) to get the last digit and then dividing the number by 10 to shift the digits to the right. The loop continues until the number becomes 0.
Here's an example of how to use this function:
```python
number = 12345
result = proddigits(number)
print("Product of digits of", number, "is", result)
```
This would output:
```
Product of digits of 12345 is 120
```
which is the product of the digits 1 x 2 x 3 x 4 x 5.