因此,我在函数内定义了两个变量,并使这些变量成为全局变量。但是,当我尝试在函数外部访问它们时,程序返回:“ 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
您必须调用函数才能定义全局变量。但实际上您实际上不需要全局变量(提示:您几乎永远不需要全局变量):
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()