因此,我在一个函数内定义了两个变量,并使这些变量成为全局变量。但是,当我尝试在函数外部访问它们时,程序返回:“ 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
答案 0 :(得分: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()