[英]Python keeps saying NameError: name 'name' is not defined
[英]It keeps saying my function is not defined in python
我正在介绍计算机编程课程,并在其中使用python。
我的任务是编写一个名为paint.py的程序,该程序将确定粉刷矩形地板棚墙的成本。 假设棚子没有窗户,油漆费用为每加仑40美元。 一加仑占地300平方英尺。 提示用户输入棚屋的尺寸。 使用名为paint_cost的函数,该函数将用户输入作为参数并返回粉刷棚墙的成本。 以货币格式表示成本。
我已经非常努力地思考如何去做。 我已经研究并在我的python书中反复阅读了这一章。 因此,如果有人可以帮助我。
def paint_cost(price):
return (dimen / 300) * 40
def main():
dimen = input('Enter the dimensions of the shed: ')
print('Your cost of painting will be $', paint_cost(price))
main()
您原始代码中的错误:
retun
应该return
paint_cost
函数中删除price
,因为您正在第2行上对其进行计算。 dimen
。
def paint_cost(dimen):
cost = (dimen / 300) * 40
return cost
def main():
dimen = int(input('Enter the dimensions of the shed: '))
print 'Your cost of painting will be $ %s' % str(paint_cost(dimen))
main()
我认为这更接近您要执行的操作:
def paint_cost(dimen):
return (dimen / 300.) * 40 # calculates cost based on dimension
def main():
dimen = int(input('Enter the dimensions of the shed: ')) ] # cast input as an integer
print('Your cost of painting will be ${}'.format(paint_cost(dimen)))# pass the dimensions to paint_cost and print using `str.format`
main()
您原始代码中的错误:
retun
应该return
所以语法错误
(dimen / 300) * 40
dimen
仅存在于main
函数中,因此未定义错误
paint_cost(price)
价格未定义,因此另一个未定义的错误
在您的行中:
print('Your cost of painting will be $', paint_cost(price))
price
尚未定义。
通常,Python会很好地描述问题所在,就像我在运行它时在这里所做的那样:
NameError: global name 'price' is not defined
还有其他问题,但是要逐步解决,要特别注意回溯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.