这可能是一个菜鸟问题,但有人可以帮助我吗? 我需要确保输入严格是浮点数。无论输入什么类型,我当前的代码都会返回错误。
pricePerCandy = float(input('Please enter the price per candy (2 decimal places): '))
if pricePerCandy.isalpha() or pricePerCandy.isalnum():
print("Please enter the price with 2 decimal places.")
pricePerCandy = float(input('Please enter the price per candy (2 decimal places): '))
答案 0 :(得分:5)
您可以编写一个简单的函数来读取输入,直到用户输入浮点值
>>> def readFloat():
... while True:
... try:
... value = float(input("Enter value "))
... return value
... except ValueError:
... print "Please enter the price with 2 decimal places"
<强>测试强>
>>> readFloat()
Enter value "asdf"
Please enter the price with 2 decimal places
Enter value "qwer"
Please enter the price with 2 decimal places
Enter value 1.2
1.2
答案 1 :(得分:1)
这个怎么样?
import re
x = input('Please enter the price per candy (2 decimal places): ')
while True:
if not re.match(r"^-?\d+.\d{2}$", x):
x = input('Please enter the price per candy (2 decimal places): ')
continue
else:
print("OK")
break
如果您不需要2位小数,则可以将其更改为re.match(r"^-?\d+.\d{1,}$", x)
答案 2 :(得分:0)
一旦你确认它可以转换为浮点数,那么请关注它是否有一个小数点,并且在该点之后至少有2个数字出现,类似这样(没有正则表达式)
def read():
while True:
try:
value = input("Enter value ")
value_f = float(value)
return value
except ValueError:
print "Please enter a valid float"
value=str(read())
point_position= value.find('.')
length_ = len(value)
required_decimal_positions = 2
if point_position>-1:
if point_position <= length_-(required_decimal_positions+1): # == if only a 2 decimal positions number is valid
print "Valid"
else:
print "No valid - No enough decimals"
else:
print "No valid - No decimal point"