NameError: name 'cost' is not defined – when calling function

NameError: name 'cost' is not defined – when calling function

我是 Python 编程的新手,在使用这个计算给定 2 个维度的瓷砖价格的简单程序时遇到了问题:

Objective: Calculate the total cost of tile it would take to cover a floor plan of width and height, using a cost entered by the user.

print ("NOTE: The unit of cost is in dollars and dimension unit is in feet")

def cost_o_tile(cost, width, height):
    while True:
        cost = int(input("Cost of each tile:"))
        width = int(input("What is the width of the floor?"))
        height = int(input("What is the height of the floor?"))
        try:
            if cost < 0 or width < 0 or height <0:
                print ("\n Please enter non-negative integers")
                break
            else:
                 return ("In order to cover your {} X {} floor, you will need to pay {} dollars".format(width,height,cost*width*height))
        except ValueError: 
            print ("No valid integer! Please try again ...")


cost_o_tile(cost, width, height)

我知道我可以在函数外部声明变量并且代码可以运行。但是,我希望这些变量在循环中,以便可以通过 except ValueError.

验证它们
cost_o_tile(cost, width, height)

当您在代码的第 18 行调用 cost_o_tile 函数时,问题出在 cost 参数上。如果你仔细观察,它没有在函数范围之外定义,因此错误。

嗯,你的函数 cost_o_lite 不应该带任何参数:

def cost_o_tile():
    ...

print(cost_o_tile())

别忘了打印结果。

您还可以分离关注点:

先写一个算法计算总费用:

def cost_o_tile(cost, width, height):
    if cost < 0 or width < 0 or height < 0:
        raise ValueError
    return cost * width * height

然后编写用户界面代码:

print ("NOTE: The unit of cost is in dollars and dimension unit is in feet")

while True:
    try:
        cost = int(input("Cost of each tile:"))
        width = int(input("What is the width of the floor?"))
        height = int(input("What is the height of the floor?"))
        total = cost_o_tile(cost, width, height)
        print("In order to cover your {} X {} floor, you will need to pay {} dollars"
              .format(width, height, total))
        break
    except ValueError:
        print ("No valid integer! Please try again ...")

使您的函数尽可能纯净是编写良好、可维护代码的关键,这当然不包括潜在的无限循环和用户输入。

全局范围内没有应有的变量 costwidthheight。这是你错误的原因。

  1. 输入代码必须移到外面
  2. 删除循环
  3. 您可以在代码运行后担心错误处理。

第一关

def cost_o_tile(cost, width, height):
    return ("In order to cover your {} X {} floor, you will need to pay {} dollars"\
                          .format(width, height, cost * width * height))

cost, width, height = map(int, input("Enter 3 space separated integers: ").split())
print(cost_o_tile(cost, width, height))

第二关

基本程序运行后,您可以查看错误处理:

def cost_o_tile(cost, width, height):
    try:
        if cost < 0 or width < 0 or height < 0:
            return "Parameters cannot be lesser than 0"
    except ValueError:
        return "Please provide numbers only"

    return ("In order to cover your {} X {} floor, you will need to pay {} dollars"\
                          .format(width, height, cost * width * height))

cost, width, height = map(int, input("Enter 3 space separated integers: ").split())
print(cost_o_tile(cost, width, height))

最终通过

现在,有了错误处理,您终于可以查看循环了。

def cost_o_tile(cost, width, height):
    try:
        if cost < 0 or width < 0 or height < 0:
            return "Parameters cannot be lesser than 0"
    except ValueError:
        return "Please provide numbers only"

    return ("In order to cover your {} X {} floor, you will need to pay {} dollars"\
                          .format(width, height, cost * width * height))

if __name__ == '__main__':
    while True:
        cost, width, height = map(int, input("Enter 3 space separated integers: ").split())
        print(cost_o_tile(cost, width, height))

        if input("Continue? ").lower() not in {'y', 'ye', 'yes'}:
            break