【问题标题】:Calling upon a locally defined variable later on python稍后在 python 上调用本地定义的变量
【发布时间】:2017-03-30 17:55:24
【问题描述】:

我试图稍后在外面回忆这些本地定义的变量(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)

【问题讨论】:

    标签: python-3.x local-variables


    【解决方案1】:

    将变量从作用域传递到作用域的一种方法是从您的函数中传递给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 — 您可以将它们分配给您工作范围内有意义的任何名称. 这就是将事物划分为函数的力量——在函数之外,您不必担心遵循函数内部使用的相同命名约定(您甚至可能不知道)。您还可以将四个输出一起分配/引用为tuple,即调用:

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

    随后将它们称为numbers[0]numbers[1]numbers[2]numbers[3]

    【讨论】:

      猜你喜欢
      • 2015-05-26
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      相关资源
      最近更新 更多