稍后在python上调用本地定义的变量

时间:2017-03-30 17:55:24

标签: python-3.x local-variables

我试图在外面回忆这些本地定义的变量(p1,p2,w1,w2)。在我的程序中,我这样做,如果用户输入的不是数字,程序会提示用户他们错误地输入了他们的响应。但是,这导致我的变量在本地定义,我不知道如何在以后使用这些本地定义的变量。非常感谢任何帮助,谢谢。

fp=input("\nWhat percentage do you want to finish the class with?")


def main():
    p1 = get_number("\nWhat is your 1st marking period percentage? ")
    w1 = get_number("\nWhat is the weighting of the 1st marking period? ")
    p2 = get_number("\nWhat is your 2nd marking period percentage? ")
    w2 = get_number("\nWhat is the weighting of the 2nd marking period? ")


def get_number(prompt):
    while True:
        try:
            text = input(prompt)
        except EOFError:
            raise SystemExit()
        else:
            try:
                number = float(text)
            except ValueError:
                print("Please enter a number.")
            else:
                break
    return number


def calculate_score(percentages, weights):
    if len(percentages) != len(weights):
        raise ValueError("percentages and weights must have same length")
    return sum(p * w for p, w in zip(percentages, weights)) / sum(weights)


if __name__ == "__main__":
    main()


mid=input("\nDid your have a midterm exam? (yes or no)")
if mid=="yes":
    midg=input("\nWhat was your grade on the midterm?")
    midw=input("\nWhat is the weighting of the midterm exam?")
elif mid=="no":
    midw=0
    midg=0
fw=input("\nWhat is the weighting of the final exam? (in decimal)")


fg=(fp-(w1*p1)-(w2*p2)-(midw*midg))/(fw)
print("You will need to get a", fg ,"on your final to finish the class with a", fp)

1 个答案:

答案 0 :(得分:0)

将变量从范围传递到范围的一种方法是从函数中return

def main():
    p1 = get_number("\nWhat is your 1st marking period percentage? ")
    w1 = get_number("\nWhat is the weighting of the 1st marking period? ")
    p2 = get_number("\nWhat is your 2nd marking period percentage? ")
    w2 = get_number("\nWhat is the weighting of the 2nd marking period? ")

    return p1, w1, p2, w2

然后,当您调用main函数时,将该函数的输出分配给适当的名称:

if __name__ == "__main__":
    p1, w1, p2, w2 = main()

请注意,您不必在此阶段将其称为p1w1p2w2 - 您可以将它们分配给任何有意义的名称在你正在使用的范围内。这就是将功能划分为函数的功能 - 你不必担心遵循函数内部使用的相同命名约定(你可能甚至不知道)。您也可以将{4}输出分配/引用作为tuple,即呼叫:

if __name__ == "__main__":
    numbers = main()

然后将其称为numbers[0]numbers[1]numbers[2]numbers[3]