我是个编程新手,我真的不明白如何使用很多这样的代码。如果有人告诉我在这种情况下如何使用global,会对我有很大的帮助。
def tshirtadd():
global perch
perch = 0
print("you have",perch,"T-shirts")
add = int(input("how many t-shirts would you like to add? "))
perch+add
return perch
def tshirtremove():
global perch
print("You have",perch,"Tshirts")
remove = int(input("How many Tshirts would you like to remove? "))
perch - remove
return perch
def order():
global perch
print(perch)
print(perch*10)
return main
def main():
ordering = int(input("Would you like to add,remove, view order, or purchase?"))
print(list1)
count = 0
for x in list1:
count = count+1
print(count,"\b)",x)
perch = 0
if ordering == 1:
tshirtadd()
print("you have",perch,"Tshirts")
return main()
elif ordering == 2:
tshirtremove()
return main()
elif ordering == 3:
order()
return main()
else:
exit
print(perch)
main()发布于 2019-12-03 12:09:18
您应该在使用global之前初始化变量perch,perch = 0应该在函数定义之前的顶部。
我认为您正在尝试初始化主函数中的perch,但这不是全局函数的工作方式,您需要在所有函数之前在外部定义它,并且您可以像其他函数一样在main()中使用全局perch,如果需要,可以在那里将其设置为零
发布于 2019-12-03 12:28:41
回答你的问题:当我们想要从任何地方访问我们的变量时,我们通常使用global。所以你只需要定义一次global variable,你就可以在任何地方使用它。
我对你的代码做了一些修改。(需要更多更改,但不确定这段代码真正想要实现的是什么)
这可能会帮助您理解global的概念
def tshirtadd():
print("you have",perch,"T-shirts")
add = int(input("how many t-shirts would you like to add? "))
perch += add
return perch
def tshirtremove():
print("You have",perch,"Tshirts")
remove = int(input("How many Tshirts would you like to remove? "))
perch -= remove
return perch
def order():
print(perch)
print(perch*10)
return main
def main():
global perch
perch = 0
ordering = int(input("Would you like to add,remove, view order, or purchase?"))
print(list1)
count = 0
for x in list1:
count = count+1
print(count,"\b)",x)
perch = 0
if ordering == 1:
tshirtadd()
print("you have",perch,"Tshirts")
return main()
elif ordering == 2:
tshirtremove()
return main()
elif ordering == 3:
order()
return main()
else:
exit
print(perch)
main()https://stackoverflow.com/questions/59149928
复制相似问题