【问题标题】:Can I get Python to evaluate an ValueError input?我可以让 Python 评估 ValueError 输入吗?
【发布时间】:2018-03-05 06:48:23
【问题描述】:

我正在创建一个代码来计算购买房屋的一些价值。它会要求用户提供大量输入,我想确保如果他们输入非整数,程序会要求他们输入整数。

我创建了一个函数来检查输入是否为整数,但如果我输入字符串,解释器只会返回值错误。输入后是否可以通过整数校验函数让它运行字符串?

var=True

print('Welcome to the interest calculator program.')

def integer_check(input):
    try:
        return True
    except ValueError:
        return False

while var==True:
    num=int(input('Enter the price of your dream house: \n'))
    if integer_check(num)==True:
        if num>=0:
            print('yay')
        elif num<=0:
            print('House price must be a positive number only. Please try again.')
    elif integer_check(num)==False:
        print("Sorry, that's not a number. Please try again.")

【问题讨论】:

  • 您确定包含正确版本的integer_check?这个版本看起来应该总是返回True

标签: python python-3.x function valueerror


【解决方案1】:

环绕try .. except .. 环绕int(..) 通话;一旦引发异常,检查 int() 调用的返回值就没有任何意义,因为如果输入字符串不是整数字符串,控制流将无法到达那里。

try:
    num = int(input('Enter the price of your dream house: \n'))
except ValueError:
    # Non-integer
else:
    # Integer

将字符串传递给函数,函数应该尝试转换为int:

print('Welcome to the interest calculator program.')

def integer_check(s):
    try:
        int(s)
        return True
    except ValueError:
        return False
    return True

while True:
    num = input('Enter the price of your dream house: \n')
    if integer_check(num):
        num = int(num)
        if num >= 0:
            print('yay')
            break
        else:  # Use else
            print('House price must be a positive number only. Please try again.')
    else:  # No need to call integer_check(..) again
        print("Sorry, that's not a number. Please try again.")

【讨论】:

    【解决方案2】:

    你可以输入 cast:

    def integer_check(i):
        try:
            int(i) # will successfully execute if of type integer
            return True
        except ValueError: # otherwise return False
            return False
    

    此外,由于您的主程序中只有通过/失败条件,请更改:

    if integer_check(num)==True:
        ...
    elif integer_check(num)==False:
        ...
    

    到:

    if integer_check(num):
        ...
    else:
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多