如何确保用户只输入了一个包含两位小数的浮点数。数字不能是4或4.999,必须是4.00或4.99否则会出现错误。
while looping:
try:
number = float(input("Number: "))
string_number = (str(number)).split(".")
check_length = len(string_number)
if check_length != 2:
print ("ERROR!")
looping = True
else:
looping = False
except ValueError:
looping = True
答案 0 :(得分:1)
您目前只检查当前只有一个小数点。
number.split(".")
将返回一个列表。如果number
为4.323
,则会返回['4', '323']
。
您真正要在if
子句中检查的是第二个元素的长度是2。
if len(string_number[1]) != 2:
答案 1 :(得分:1)
检查号码的第二部分。
while True:
try:
number = input('Number:')
integral, fractional = number.split('.')
number = float(number)
if len(fractional) == 2:
break
except ValueError:
pass
print('ERROR!')
答案 2 :(得分:0)
looping = True
while looping:
number = input("Number: ")
string_number = number.split(".")
if len(string_number) != 2:
print ("ERROR: Needs exactly one decimal point!")
looping = True
elif len(string_number[1]) != 2:
print ("ERROR: Two numbers are required after decimal point!")
looping = True
else:
try:
number = float(number)
looping = False
except ValueError:
print("ERROR: Number is not valid!")
looping = True
进行一些小的更改消除了变量looping
的需要。由于我们的目标是获得有效数字,我们可以测试一下:
number = None
while not number:
s = input("Number: ")
string_number = s.split(".")
if len(string_number) != 2:
print ("ERROR: Needs exactly one decimal point!")
continue
elif len(string_number[1]) != 2:
print ("ERROR: Two numbers are required after decimal point!")
continue
try:
number = float(s)
except ValueError:
print("ERROR: Number is not valid!")
答案 3 :(得分:0)
我会这样写:
while True:
try:
str_num=input("Number: ")
num=float(str_num) # ValueError if cannot be converted
i, f=str_num.split('.') # also ValueError if not two parts
if len(f)==2:
break # we are done!!!
except ValueError:
pass
print('ERROR! ') # either cannot be converted or not 2 decimal places
print(num)