Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的数学错误导致TypeError_Python - Fatal编程技术网

python中的数学错误导致TypeError

python中的数学错误导致TypeError,python,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

在我输入每加仑油漆的价格后,程序崩溃了。谁能告诉我我的代码有什么问题吗?我正在使用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' 
回溯(最近一次呼叫最后一次):
main()中第21行的文件“D:\Users\harve\u 000\Desktop\Painting.py”
文件“D:\Users\harve\u 000\Desktop\Painting.py”,第9行,主估算(平方英尺,价格/加仑)
文件“D:\Users\harve\u 000\Desktop\Painting.py”,第13行,估计数加仑=平方英尺/115
TypeError:/:“str”和“int”的操作数类型不受支持

它崩溃,因为默认情况下,
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)

您需要将
输入
转换为
int
,尝试使用字符串执行算术,还应该发布完整的回溯,而不是告诉我们它崩溃了,知道它在哪里很有用crashes@EdChum:铸造的需要取决于OP使用的版本。我们不能确定这是否正确,这个脚本是在Python2.7.9中运行的。但是,您还需要将115替换为115.0,以确保数学计算正确。@AswinMurugesh您是说python的版本吗?我假设在
打印
statement@EdChum:因此,如果OP使用
input()
语句,Python 2.7不需要强制转换