python中的数学错误导致TypeError

时间:2015-09-04 08:09:05

标签: python

在我输入每加仑油漆价格后,程序崩溃了。谁能告诉我我的代码有什么问题?我正在使用python。

 def main():

    # Ask for the square footage of wall space to be painted.
    square_footage = input('Enter the number of square feet to be painted: ')

    # Ask for the price of the paint per gallon.
    price_gallon = input('Enter the price of the paint per gallon: ')

    estimate(square_footage, price_gallon)

def estimate(square_footage, price_gallon):
    # 115 sq ft = 1 gallon + 8 hrs of labor (labor is $20 per hour)
    num_gallons = square_footage/115
    hours_labor = num_gallons * 8
    total_price_gallon = num_gallons * price_gallon
    total_labor = hours_labor * 20
    final_total = total_price_gallon + total_labor
    print 'The total estimated price for this paint job is $', final_total

# Call the main function.
main()

错误信息:

Traceback (most recent call last): 
    File "D:\Users\harve_000\Desktop\Painting.py", line 21, in <module> main() 
    File "D:\Users\harve_000\Desktop\Painting.py", line 9, in main estimate(square_footage, price_gallon) 
    File "D:\Users\harve_000\Desktop\Painting.py", line 13, in estimate num_gallons = square_footage/115 
    TypeError: unsupported operand type(s) for /: 'str' and 'int' 

1 个答案:

答案 0 :(得分:1)

崩溃因为默认input()返回一个字符串而不是整数/浮点数,因此你需要更改它。

def main():

    # Ask for the square footage of wall space to be painted.
    square_footage = float(input('Enter the number of square feet to be painted: '))

    # Ask for the price of the paint per gallon.
    price_gallon = float(input('Enter the price of the paint per gallon: '))

    estimate(square_footage, price_gallon)