无法访问函数内部的变量吗?

问题描述 投票:-3回答:1

因此,我在函数内定义了两个变量,并使这些变量成为全局变量。但是,当我尝试在函数外部访问它们时,程序返回:“ NameError:未定义名称'mon_price'”。

这里是参考代码:

def seq_1():
    global mon_price, sun_price
    mon_price = int(input("Enter the selling price per turnip on monday morning: "))
    sun_price = int(input("Enter the sale's price per turnip on sunday: "))


x = mon_price / sun_price
python function variables global-variables
1个回答
2
投票

您必须调用函数才能定义全局变量。但实际上您实际上不需要全局变量(提示:您几乎永远不需要全局变量):

def seq_1():
    mon_price = int(input("Enter the selling price per turnip on monday morning: "))
    sun_price = int(input("Enter the sale's price per turnip on sunday: "))
    return mon_price, sun_price


def main():
   mon_price, sun_price = seq_1()
   x = mon_price / sun_price
   print("x = {}".format(x))


if __name__ == "__main__":
    main()
© www.soinside.com 2019 - 2024. All rights reserved.