python

时间:2017-01-21 00:04:28

标签: python

我正在接受udemy的教程来自学Python,这让我每天都更喜欢Javascript。无论如何,我似乎无法弄清楚如何正确处理这个缩进,以便程序在while循环中运行,该循环评估零字符串以退出但是所有输入和计算必须在函数内部。

我已经做到这一点,但是重量,高度和bmi变量都抛出了未定义的错误。问题是,据我所知,我没有在他们的功能中定义它们吗?

  

NameError:未定义名称'weight'

所以,我想,也许是因为我需要缩进函数调用来为变量声明提供更高的范围,你知道什么!邪恶的红色波浪形下划线消失了。所以我运行程序时没有任何错误,但是在while循环中没有运行。它忽略了一切!啊....

请帮忙。上帝,我喜欢弯曲的括号和分号。

def BMICalculator():
    student_name = input("Enter the student's name or 0 to exit:")
    while student_name != "0":
        def getWeight():
            weight = float(input("Enter " + student_name + "'s weight in pounds: "))
            return weight

        def getHeight():
            height = float(input("Enter " + student_name + "'s height in pounds: "))
            return height

        def calcBMI(weight, height):
            bmi = (weight * 703) / (height * height)
            return bmi

        getWeight()
        getHeight()
        calcBMI(weight, height)
        print("\n" + student_name + "'s BMI profile:")
        print("---------------")
        print("Height:", height, "\nWeight:", weight)

        def showBMI(bmi):
            print("BMI Index:", "{:.2f}".format(bmi))

        showBMI(bmi)

        student_name = input("Enter next student's name or 0 to exit:")


    print("\n\nExiting Program!")


BMICalculator()

3 个答案:

答案 0 :(得分:3)

你正在获得体重,身高和体重,但你只是丢掉了结果。这些变量是内部函数作用域的局部变量,因此它们对于外部函数是不可见的。

这样做的:

weigth = getWeight()
height = getHeight()
bmi    = calcBMI(weight, height)

解决问题。

另外,关于波浪形括号和分号的说明;在Python中,具有相同缩进级别的缩进块相当于其他语言中的一对波浪形括号。换行符转换为分号。

    a = 1
    b = 2
    if True:
        c = 3

< =>

{
    a = 1;
    b = 2;
    if (True) {
        c = 3;
    }
}

但是,有一些(方便的)例外。就像在没有右括号的情况下结束一行时,不会插入“虚拟分号”。此外,内部Python作用域不会将其局部变量隐藏到外部作用域,除非作用域是由函数引起的。

答案 1 :(得分:2)

  

我没有在他们的功能中定义它们

是的,这就是问题所在。它们是本地范围的功能。您需要分配... weight = getWeight(),例如

不需要过分使用函数定义,但

def calcBMI(weight, height):
    bmi = (weight * 703) / (height * height)
    return bmi

def showBMI(bmi):
    print("BMI Index:", "{:.2f}".format(bmi))

student_name = input("Enter the student's name or 0 to exit:")
while student_name != "0":
    weight = float(input("Enter " + student_name + "'s weight in pounds: "))
    height = float(input("Enter " + student_name + "'s height in pounds: "))

    bmi = calcBMI(weight, height)

    # etc...

    showBMI(bmi)
    student_name = input("Enter next student's name or 0 to exit:")

print("\n\nExiting Program!")

答案 2 :(得分:1)

您正在访问范围之外的变量。例如,权重变量在getWeight()函数的范围内定义,但您尝试从BMICalculator()范围访问它。

快速解决方案

您应该适当调整变量范围,您有两种选择。将函数定义为闭包或仅使用返回值。 下面我是如何第二个选项。

def BMICalculator():
    student_name = input("Enter the student's name or 0 to exit:")
    while student_name != "0":
        def getWeight():
            weight = float(input("Enter " + student_name + "'s weight in pounds: "))
            return weight

        def getHeight():
            height = float(input("Enter " + student_name + "'s height in pounds: "))
            return height

        def calcBMI(weight, height):
            bmi = (weight * 703) / (height * height)
            return bmi

        # here you have to define the weight, height and bmi
        # variables in this scope.
        weight = getWeight()
        height = getHeight()
        bmi = calcBMI(weight, height)
        print("\n" + student_name + "'s BMI profile:")
        print("---------------")
        print("Height:", height, "\nWeight:", weight)

        def showBMI(bmi):
            print("BMI Index:", "{:.2f}".format(bmi))

        showBMI(bmi)

        student_name = input("Enter next student's name or 0 to exit:")


    print("\n\nExiting Program!")

评论

为了澄清,你应该尝试在循环之外移动函数(将它们放在与BMICalculator()相同的级别。这可能会澄清你的范围问题。

def getWeight():
    weight = float(input("Enter " + student_name + 
                         "'s weight in pounds: "))
    return weight

def getHeight():
    height = float(input("Enter " + student_name + 
                         "'s height in pounds: "))
    return height

def calcBMI(weight, height):
    bmi = (weight * 703) / (height * height)
    return bmi

def BMICalculator():
    student_name = input("Enter the student's name or 0 to exit:")
    while student_name != "0":
        # Now it is more evident that the weight, height and bmi
        # variables in the above functions are only defined in the
        # scope of the respective function, the BMICalculator scope
        # is different and the names "weight", "height" and "bmi" are
        # not bound to anything, hence the NameError.
        weight = getWeight()
        height = getHeight()
        bmi = calcBMI(weight, height)
        print("\n" + student_name + "'s BMI profile:")
        print("---------------")
        print("Height:", height, "\nWeight:", weight)

        def showBMI(bmi):
            print("BMI Index:", "{:.2f}".format(bmi))

        showBMI(bmi)

        student_name = input("Enter next student's name or 0 to exit:")

在python中确定范围有一些简单而重要的规则,我建议您查看this答案,快速了解范围解析。

顺便说一句,你遇到的问题与python无关,任何体面的(或者至少是我所知道的)编程语言(甚至是javascript)都会将这些变量视为超出范围。

希望这有帮助。