在python中创建新函数时名称错误
import math
def paint_calc(height, width, coverage):
area= height * width
num_of_cans= math.ceil(area/coverage)
width = int(input("What is the width?"))
height = int(input("What is the height?"))
coverage = 5
paint_calc(width, height, coverage)
print(f'You need {num_of_cans} of paint')
我在 python 中创建了一个新函数,但第二个变量给了我一个名称错误,并且当我尝试运行代码时未定义 num_of_can 。
import math
def paint_calc(height, width, coverage):
area= height * width
num_of_cans= math.ceil(area/coverage)
width = int(input("What is the width?"))
height = int(input("What is the height?"))
coverage = 5
paint_calc(width, height, coverage)
print(f'You need {num_of_cans} of paint')
I made a new function in python but the second variable is giving me a name error and num_of_can is not defined when I try to run the code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您在函数内部定义变量时,它的作用域是函数体。因此,如果您尝试在其范围之外使用它,将会导致错误。
由于 num_of_cans 是在函数内定义的,因此一旦该函数执行完毕,该变量就会消失。
您可以做的是从函数返回 num_of_cans 并在外部作用域中重新定义它。
像这样:
When you define a variable inside of a function it is scoped to that the function body. So if you attempt to use it outside it's scope, it will cause an error.
Since
num_of_cans
is defined within a function, once that function is finished executing the variable goes away.What you could do is return
num_of_cans
from the function and redefine it in the outer scope.Like this: