1

想知道是否有更好的方法来做到这一点。Python 是我的第一门编程语言。

while True:
    amount_per_month = raw_input('\nWhat is the monthly cost?\n==> ')
    # seperate dollars and cents.
    amount_list = amount_per_month.split(".")
    # checking if int(str) is digit
    if len(amount_list) == 1 and amount_list[0].isdigit() == True:
        break
    # checking if float(str) is digit
    elif len(amount_list) == 2 and amount_list[0].isdigit() and amount_list[1].isdigit() == True:
        break
    else:
        raw_input('Only enter digits 0 - 9.  Press Enter to try again.')
        continue
4

3 回答 3

7

float如果无法转换,请尝试将其设置为并处理引发的异常。

try:
    amount_per_month = float( raw_input('What is the monthly cost?') )
except (ValueError, TypeError) as e:
    pass # wasn't valid

TypeError在这里是多余的,但如果转换是在其他 Python 对象(不仅仅是字符串)上进行的,则需要捕获float( [1, 2, 3] ).

于 2012-10-17T00:25:31.530 回答
0

您可以尝试将输入转换为浮点数,并在输入无效时捕获异常:

amount_per_month = raw_input('\nWhat is the monthly cost?\n==> ')
try:
    amt = float(amount_per_month)
except ValueError:
    raw_input('Only enter digits 0 - 9.  Press Enter to try again.')
于 2012-10-17T00:27:44.687 回答
0

使用正则表达式

r'\d+.\d+|\d+'

http://docs.python.org/library/re.html

于 2012-10-17T00:37:46.200 回答