【发布时间】:2022-01-22 00:53:17
【问题描述】:
我正在尝试使用此代码来计算面积成本。我正在使用函数选项,但它说 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
【问题讨论】:
-
price在哪里定义在cost(或全局)?我看不到price对cost可见的定义。就此而言,我看不到在哪里调用了cost(),这意味着这不是 minimal reproducible example。 -
@Shadow
cost()在最后一行被调用。但是否则你是对的,price显然对cost()是不可见的,而且这段代码绝对不是最小的。 -
错误消息显示
price()未定义,而不是cost()。这是因为该名称的变量未在该函数中定义(也不是全局定义)。flooring()按该名称定义一个 local 变量,但cost()看不到它。 -
@wjandrea:糟糕,错过了滚动条。 :-)