【发布时间】:2020-10-23 21:56:57
【问题描述】:
我有一个接受值 1-5 的函数,我想声明一个名为“Des”的全局变量,并根据所选选项对其进行更改,因为我想在另一个函数中使用该值。我试过了,但它不起作用。
def mainNJ():
#S_menu()
print( "\033[1m" " PLEASE SELECT THE TYPE OF DONATION.")
global Des
validate = False
while not validate:
option = input(" INPUT VALUE 1 TO 5 : " "\033[0m")
# For Selection 1 Animal Protection And Welfare.
if option == str(1):
validate = True
print()
print("\033[1m" " Animal Protection And Welfare Has Been Selected." "\033[0m")
#Amount()
Des1 = " Animal Protection And Welfare Has Been Selected."
Des = Des1
# For Selection 2 Support For Natural Disaster.
elif option == str(2):
validate = True
print()
print("\033[1m" " Support For Natural Disaster Has Been Selected." "\033[0m")
#Amount()
Des2 = " Support For Natural Disaster Has Been Selected."
Des = Des2
# For Selection 3 Children Education And Activities.
elif option == str(3):
validate = True
print()
print("\033[1m" " Children Education And Activities Has Been Selected." "\033[0m")
#Amount()
Des3 = " Children Education And Activities Has Been Selected."
Des = Des3
# For Selection 4 Children Education And Activities.
elif option == str(4):
validate = True
print()
print("\033[1m" " Caregiving And Health Research Has Been Selected." "\033[0m")
#Amount()
Des4 = " Caregiving And Health Research Has Been Selected."
Des = Des4
# For Selection 5 Conservation Of Cultural Arts.
elif option == str(5):
validate = True
print()
print("\033[1m" " Conservation Of Cultural Arts Has Been Selected." "\033[0m")
#Amount()
Des5 = " Conservation Of Cultural Arts Has Been Selected."
Des = Des5
else:
print()
print(" Invalid Option. Please Try Again.")
#S_menu()
【问题讨论】:
-
对 Amount 和 S_Menu 的调用是否与问题相关?如果没有,您可能希望将它们从您的代码中删除,因为它们会阻止其他人按原样运行它。
-
@Roy2012 注意,我已将它们注释掉。
-
用类代替全局变量怎么样?
-
为什么您认为您的代码不起作用? Des 在您的代码末尾分配了一个值。
-
作为一名程序员,你应该非常、非常、非常努力不使用全局变量。
标签: python python-3.x loops if-statement