繁体   English   中英

更改 IF 循环内的变量值

[英]changing variable value inside IF loop

我有一个接受值 1-5 的 function,我想声明一个名为“Des”的全局变量并根据选择的选项对其进行更改,因为我想在另一个 function 中使用该值。 我试过这个,但它不起作用。

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()

您将 Des 分配给 Desx,这是一个字符串。 您需要将其分配给 int(option)

也许,如果 Des 没有在 function 之外定义,那么您正试图在分配 > > 之前访问它。 即在调用 mainNJ() 之前,你正在对 Des 做一些事情

给出解决方案,如果这是问题

在另一个 function 中使用它

try:
    print(Des) # example of usage
except NameError: 
    print("Des not yet created")
    # also you can put return statement so function does not continue
    # or call mainNJ() here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM