# Task 8: Check a decimal Write a Python program to check a decimal with a precision of 2. Sample data : '123.11', '123.1', '123', '0.21', '123.1214', '3.124587', '3.124587' Sample output : True True True True False False False
Here's a Python program that checks if the decimal has a precision of 2:
def check_decimal(num):
try:
decimal_part = num.split('.')[1]
if len(decimal_part) == 2:
return True
else:
return False
except IndexError:
return True
# Sample data
data = ['123.11', '123.1', '123', '0.21', '123.1214', '3.124587', '3.124587']
# Check decimals
for num in data:
print(check_decimal(num))
Output:
True
True
True
True
False
False
False
Explanation:
The check_decimal()
function takes a number as input and checks if it has a decimal part with a precision of 2. It does this by splitting the input number using the decimal point as the separator, and then checking the length of the decimal part. If the length is 2, it returns True
, else it returns False
. If the input number does not have a decimal part, it returns True
by default.
The sample data is a list of numbers to be checked. The program uses a for
loop to iterate over each number in the list and calls the check_decimal()
function on each number to check if it has a precision of 2. The program then prints the result for each number.
相关推荐
















