當我在Python編程新手,有這個簡單的程序,計算瓷磚價格給予2個維度麻煩:NameError:名字「成本」是沒有定義 - 調用函數
Objective: Calculate the total cost of tile it would take to cover a floor plan of width and height, using a cost entered by the user.
print ("NOTE: The unit of cost is in dollars and dimension unit is in feet")
def cost_o_tile(cost, width, height):
while True:
cost = int(input("Cost of each tile:"))
width = int(input("What is the width of the floor?"))
height = int(input("What is the height of the floor?"))
try:
if cost < 0 or width < 0 or height <0:
print ("\n Please enter non-negative integers")
break
else:
return ("In order to cover your {} X {} floor, you will need to pay {} dollars".format(width,height,cost*width*height))
except ValueError:
print ("No valid integer! Please try again ...")
cost_o_tile(cost, width, height)
我理解我可以在函數之外聲明變量,並且代碼可以工作。但是,我想在循環內部使用這些變量,因此可以通過except ValueError
進行驗證。
你在哪裏定義成本?如果這就是你想要計算的成本,爲什麼你要花費呢?當你寫'cost_o_tile(cost,width,height)'時,你在給函數數據。 – Carcigenicate
@Carcigenicate:他每個瓷磚的成本(作爲參數傳遞)和整層的成本(他正在計算的)。 –
@HughBothwell Ah – Carcigenicate