在python中创建新函数时名称错误

发布于 2025-01-15 05:25:03 字数 392 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

软糯酥胸 2025-01-22 05:25:03

当您在函数内部定义变量时,它的作用域是函数体。因此,如果您尝试在其范围之外使用它,将会导致错误。

由于 num_of_cans 是在函数内定义的,因此一旦该函数执行完毕,该变量就会消失。

您可以做的是从函数返回 num_of_cans 并在外部作用域中重新定义它。

像这样:

import math
def paint_calc(height, width, coverage):
    area= height * width
    num_of_cans= math.ceil(area/coverage)
    return num_of_cans   # return the calculated value


width = int(input("What is the width?"))
height = int(input("What is the height?"))
coverage = 5
num_of_cans = paint_calc(width, height, coverage)   # redefine variable 
print(f'You need {num_of_cans} of paint')

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:

import math
def paint_calc(height, width, coverage):
    area= height * width
    num_of_cans= math.ceil(area/coverage)
    return num_of_cans   # return the calculated value


width = int(input("What is the width?"))
height = int(input("What is the height?"))
coverage = 5
num_of_cans = paint_calc(width, height, coverage)   # redefine variable 
print(f'You need {num_of_cans} of paint')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文