I'm trying to limit input values to one decimal place. If the user inputs more than one decimal places in the input value, output an error sentence in the program.
Without using a rounding function, I want my program to only work with 1st decimal places and integers.
CodePudding user response:
First, you need to check if the input is convertible to float
, then validate the decimal place.
def decimal():
try:
number = float(input("Type in your number: "))
if number not in [round(number, i) for i in [0, 1]]:
print("Your number should have less than one decimal place.")
else:
print("No errors were detected.")
return number
except ValueError:
print("Your input is not convertible to type float.")
Results
Let's try a few test cases on the decimal
function.
Type in your number: 5.98
ValueError: Your number should have less than one decimal place.
Type in your number: 10.7
No errors were detected.
It also works with negative values.
Type in your number: -8
No errors were detected.
Input of type str
is not convertible to type float
.
Type in your number: Python
ValueError: Your input is not convertible to type float.
CodePudding user response:
You can try this:
value = float(input("Input your number: "))
if (value * 10) % 1 == 0:
print(value)
else:
print("Only enter up to 1 decimal point")
Essentially we are checking if the value entered (times 10 to get a whole number) has a remainder. If there's no remainder, we are just printing the value, otherwise, an error message pops up.
Output:
Input your number: 1.2
>>> 1.2
Input your number: 6.42
>>> Only enter up to 1 decimal point
CodePudding user response:
We need to take the input from user say n. If it has one decimal place, then n*10
should be int
, else it has more than 1 decimal places. My code:
n=float(input ("Enter n= "))
if n*10==int(n*10):
print("Correct")
else:
print("Invalid input")