我正在嘗試使用此代碼來計算面積成本。我正在使用函式選項,但它說cost沒有定義,我確實定義了它。
def space():
""" This function will calculate the area of floor, that needs
flooring. """
# asking for variables
length =int(input('Please enter the length of the room in meters: '))
width =int(input('Please enter the width of the room in meters: '))
area=length*width
return area
def flooring():
"""This function will take the flooring chosen by the user and will
return the cost of the square meter."""
while True:
# asking for variables
opt=int(input('Please select type of flooring: '))
if (opt>=1 and opt<=5):
break
if (opt==1):
price=18.75
...
return price
def cost():
"""This will calculate the cost of the flooring, and other costs, and
will display them, aligned."""
print(price)
matCost=area*price
print("$",matCost)
###
### MAIN PROGRAM
###
while True:
...
space()
print()
print('Types of Flooring')
print()
print(' Cost per sq.m.')
print('1. Low Pile Carpet $18.75')
...
flooring()
print()
cost()
錯誤說,但我認為我已經定義了它。使用 opt 的 if 陳述句,我以為我已經定義了。
Traceback (most recent call last):
File"main.py", line 80 in <module>
cost()
File"main.py", line 52 in <module>
print(price)
NameError: name 'price' is not defined
uj5u.com熱心網友回復:
我想你只是忘了在上面加上價格 def cost():
def cost(price):
"""This will calculate the cost of the flooring, and other costs, and
will display them, aligned."""
print(price)
matCost=area*price
print("$",matCost)
price_result = flooring()
cost(price_result)
uj5u.com熱心網友回復:
因為 price 變數是在函式內部定義的,所以它不是全域變數。您必須呼叫回傳所述價格變數的 floor 方法,而不是嘗試直接呼叫價格變數。
def cost():
"""This will calculate the cost of the flooring, and other costs, and will display them, aligned."""
price = flooring()
# The area variable is also not defined outside of the space method so it would be a good idea to add this as well.
area = space()
print(price)
matCost=area*price
print("$",matCost)
解決樓層型別重復詢問的問題:
在下面的代碼塊中,print(flooring())陳述句正在呼叫 floor 函式,因此,重新運行input()
要解決此問題,您必須更改以下代碼塊:(閱讀評論!)
while True:
...
space()
print()
print('Types of Flooring')
print()
print(' Cost per sq.m.')
print('1. Low Pile Carpet $18.75')
...
# Set price variable to the flooring() method the first time you call it!
price = flooring()
print()
cost()
設定全域價格變數后,在函式中使用,如圖:
def cost():
"""This will calculate the cost of the flooring, and other costs, and
will display them, aligned."""
#using the global price variable
print(price)
matCost=space()*flooring()
print("$",matCost)
另外,如果您在意,請注意,當輸入的地板型別不是 1 時,代碼會引發錯誤,因此您可能想要列印類似“無效的地板型別”之類的內容:
if (opt==1):
price=18.75
else:
price="Invalid flooring type"
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/418837.html
標籤:
